C++ 在类内重载cout运算符时出现编译错误
在类内重载cout运算符时出现编译错误C++ 在类内重载cout运算符时出现编译错误,c++,C++,在类内重载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<<
#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;
}
我错过了什么
下面是源代码。当我在类之外定义重载操作符时,问题就消失了
#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;
}
#包括
使用名称空间std;
类框{
公众:
int l,b,h;
方框(整数长度,整数宽度,整数高度):l(长度),b(宽度),h(高度){}
#如果1
ostream&operator成员函数:
ostream& operator<<(ostream& os);
std::ostream& operator<<(std::ostream& os, const Box& inb) {
os << (inb.l * inb.b * inb.h);
return os;
}
ostream&operator你不能重载operator表达式X,这不是重载运算符的方法。但是如果我添加了friend关键字,编译就可以了fne@MOHAMED如果是这样的话,你真正的框
定义与你在问题中的定义不同。如果你使用框
定义正如在问题中一样,它在没有friend
的情况下工作:-但是确保运算符变量在我的类中是公共的。我使用了你的函数,但仍然不工作。我添加了friend关键字和编译工作now@MOHAMED我不明白你的评论(或你对我的回答的评论)。此答案已成为朋友
。您在何处向此答案添加了朋友
关键字?
ostream& operator<<(ostream& os) {
os << (l * b * h);
return os;
}
ostream& operator<<(Box& this_, ostream& os) {
os << (this_.l * this_.b * this_.h);
return os;
}
B << cout << endl;
class Box {
public:
Box(int length, int breadth, int height) : l(length), b(breadth), h(height) {}
friend std::ostream& operator<<(ostream& os, const Box& box) {
os << (box.l * box.b * box.h);
return os;
}
private:
int l, b, h;
};