【发布时间】:2021-05-05 11:46:15
【问题描述】:
我对 c++ 很陌生,我目前的问题是使用重载运算符输出 struct。 我已经尽力了,但显然还不够。任何人都知道为什么我的编译器不断推出这个错误: \main.cpp|16|error: no match for 'operator
这是对应的代码:
#include <iostream>
#include <string>
using namespace std;
enum class Eyecolor {blue, brown, green};
struct PStruct {
string surname;
Eyecolor eyecolor;
double height;
bool gender;
friend std::ostream& operator<<(std::ostream& os, const PStruct& ps);
};
std::ostream& operator<<(std::ostream& os, const PStruct& ps)
{
os << ps.surname << '/' << ps.height << '/' << ps.gender << '/' << ps.eyecolor; //line 16
return os;
}
void print(){
cout << os;
}
int main()
{
return 0;
}
我很确定我在此之前定义了运算符
还是先谢谢大家的回答
【问题讨论】:
-
您没有为您的
enum Eyecolor定义operator<< -
例如究竟是什么错误。
(operand types are 'std::basic_ostream' and 'const Eyecolor')。您在PSStruct上定义了您的运算符。但是您的枚举是类类型。如果你想让<< ps.eyecolor工作,它需要自己的运算符。 -
好吧,正如 WhozCraig 所说,或者您可以进行切换(或如果)而不是“godbolt.org/z/TEf8bds8v
-
@MathiasJ; 1)你的例子被打破了。 2) 不好的建议。
-
@user1810087 是的,因为给出的示例代码被破坏了?该问题与特定的编译器错误有关,此代码修复了该编译器错误。它没有解决“void print(){ cout
标签: c++ operator-keyword