Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在类内重载cout运算符时出现编译错误_C++ - Fatal编程技术网

C++ 在类内重载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<<

在类内重载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;
}
我错过了什么

下面是源代码。当我在类之外定义重载操作符时,问题就消失了

#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;
};