【问题标题】:Operator Overloading to display User defined data types [duplicate]运算符重载以显示用户定义的数据类型
【发布时间】:2019-02-01 05:45:05
【问题描述】:

我在研究结构时遇到了这个问题。

#include<iostream>
#include<string>
#include<vector>


using namespace std;

struct entry
{
    string name;
    int number;
};


int main()
{
    vector<entry> adres{{"Noname",212345},{"Yesname",7564745}};

    for(x:adres)
    {
        cout<<x<<endl;
    }

}

这只是一个测试代码!

所以我创建了一个结构并想在我的向量中使用它。 C++ 给了我这个错误

error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'entry')|

经过一番搜索,我发现我需要重载

我的问题是我该怎么做?我怎样才能重载“

【问题讨论】:

  • “这只是一个测试代码!” - 您能否发布代码,仅显示您所询问的问题? for(x:adres) 不是格式良好的循环,会导致完全不相关的错误。请阅读有关创建minimal reproducible example 的更多信息。

标签: c++ operator-overloading operators ostream


【解决方案1】:

您可以像这样重载&lt;&lt; 运算符。

std::ostream& operator<<(std::ostream& out, const entry& e) {
    out << "Name: " << e.name << ", Number: " << e.number;
    return out;
}

【讨论】:

  • 对于有私人会员的班级,您想流式传输,请让&lt;&lt;成为班级的朋友。
  • 对不起,我无法早点回复,这几天有太多的互联网问题
猜你喜欢
  • 2013-09-06
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2021-10-16
  • 1970-01-01
  • 2022-07-04
  • 2016-12-14
相关资源
最近更新 更多