gpt4 book ai didi

c++ - 当我在类中重载 cout 运算符时出现编译错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:13 25 4
gpt4 key购买 nike

在类中重载 cout 运算符时出现编译错误

我错过了什么?

在源代码之后。当我在类外定义重载运算符时,问题就消失了

#include <iostream>
using namespace std;

class Box {
public:
int l, b, h;
Box(int length, int breadth, int height) : l(length), b(breadth), h(height) {}
#if 1
ostream& operator<<(ostream& os) {
os << (l * b * h);
return os;
}
#endif
};

#if 0
ostream& operator<<(ostream& os, Box inb) {
os << (inb.l * inb.b * inb.h);
return os;
}
#endif


int main(void) {
Box B(3,4,5);
cout << B << endl;
return 0;
}

最佳答案

成员函数:

ostream& operator<<(ostream& os);

在这种情况下会有用:

boxobject << os;

这很少是您想要做的。相反,您需要这个免费功能:

std::ostream& operator<<(std::ostream& os, const Box& inb) {
os << (inb.l * inb.b * inb.h);
return os;
}

关于c++ - 当我在类中重载 cout 运算符时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59177564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com