当我在类中重载 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;
}
Run Code Online (Sandbox Code Playgroud)
成员函数:
ostream& operator<<(ostream& os);
Run Code Online (Sandbox Code Playgroud)
在这种情况下会很有用:
boxobject << os;
Run Code Online (Sandbox Code Playgroud)
这很少是你想做的。相反,您需要这个免费功能:
std::ostream& operator<<(std::ostream& os, const Box& inb) {
os << (inb.l * inb.b * inb.h);
return os;
}
Run Code Online (Sandbox Code Playgroud)