首页 文章

为什么C有自定义结构向量的ostream重载问题?

提问于
浏览
0

我编写了一个代码,它必须迭代一个向量并打印其内容 . 我收到一个错误:

dfs.cpp:45:16:错误:'operator *'不匹配(操作数类型是'const traits')std :: cout << * c <<''; dfs.cpp:44:15:错误:无法将'std :: ostream '左值绑定到'std :: basic_ostream &&'std :: cout << * v <

但是,迭代适用于char类型的向量

#include<iostream>
#include<list>
#include<vector>
#include<stdio.h>

using namespace std;

struct traits
{
    int x;
    bool visit;
    std::list<int> friends;
};

int main()
{
    cout << "Enter the number of employees: " << endl;
    int noOfEmployees, noOfFriends;
    cin>>noOfEmployees;
    std::vector<traits> employees;
    int i = 0; int j;
    while(noOfEmployees--){
        traits v;
        v.x = i;
        cout << "Enter the no of friends: " << endl;
        cin >> noOfFriends;
        while(noOfFriends--){
            cin>>j;
            v.friends.push_back(j);
        }
        v.visit = false;
        employees.push_back(v);
    }

    std::vector<char> path;
    path.push_back('a');
    path.push_back('l');
    path.push_back('i');
    path.push_back('a');
    for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i){
        std::cout << *i << ' ';
    }
    for(std::vector<traits>::iterator v = employees.begin(); v != employees.end(); ++v){
        std::cout<<*v<<endl;
    }
}

我已经看到了很少的答案,但我想在没有运算符重载的情况下做到这一点,那么正确的或更多的C -nic方式是什么?

2 回答

  • 1

    您得到的错误告诉您ostream运算符没有规则应用于 trait 类型的对象 . 执行此操作的最多方法是重载 << 运算符,但您想要这样做.2394560_t .

    鉴于该约束,您可以将 traits 项转换为ostream运算符支持的内容 . 执行此操作的合理方法是使用命名空间级别,非成员函数

    std::string to_string(const traits& t) {
    /// Code to generate a string representation of your traits object
    }
    for (const auto emp& : employees){
        std::cout<< to_string(emp) << ' ';
    }
    

    如果我在 生产环境 中看到这样的代码,我会期望作者有理由不使用更规范的运算符重载,如果他们没有,我会感到失望 .

  • 3

    使用 iostream operators <<>>istreamostream 时,它是 coutcinifstreamofstreamfstream 对象以编译器的方式或编写编译器的方式来考虑它...

    这些是模板类型 . 用户将创建具有可以内置或自定义用户定义的各种类型的模板 . 为了给用户提供这种能力,编译器如何知道你的情况下 ostream 将使用 listlist<float>list<yourType> ?因此,您必须自己为要支持 operator>>()operator<<() 的所有类型创建重载 . 当用户Spacemoose击败我时;您必须通过独立函数将基础类型转换为已经与运算符一起使用的类型 .

相关问题