【问题标题】:Why does C++ have an ostream overloading issue with customised struct vectors?为什么 C++ 有自定义结构向量的 ostream 重载问题?
【发布时间】:2018-11-01 23:54:53
【问题描述】:

我编写了一个代码,它必须遍历一个向量并打印它的内容。我收到一个错误:

dfs.cpp:45:16: error: no match for ‘operator*’ (operand type is ‘const traits’) std::cout

但是,迭代适用于 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 方式?

【问题讨论】:

  • traits需要重载operator&lt;&lt;,或者自己打印出traits的内容。
  • 为什么你刚刚创建的类型会有一个内置的operator&lt;&lt;char 是语言的一部分,当然支持打印出来。
  • 标准容器不存在,你必须自己写一个重载。
  • 提供有效的代码并为您未显示的代码提供错误消息没有多大意义。请提供minimal reproducible example。谢谢。

标签: c++ vector


【解决方案1】:

当使用iostream operators &lt;&lt;&gt;&gt; 来表示istreamostream 时,可以考虑coutcinifstreamofstreamfstream 对象它以编译器或编写编译器的方式...

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

【讨论】:

    【解决方案2】:

    您得到的错误是告诉您 ostream 运算符没有适用于 trait 类型对象的规则。执行此操作的最“C++nic”方法是重载 &lt;&lt; 运算符,但您已经说过您不想这样做。

    鉴于该约束,您可以将 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) << ' ';
    }
    

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

    【讨论】:

    • "nic" 绝对不是这里使用的后缀。过于努力地模仿 pythonic 这个词?
    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多