简体   繁体   English

为什么我的编译器在我重载增量运算符时会出错

[英]why my compiler give error when i overload increment operator

I am facing a problem in operator overloading, when I compile my program it gives me an error, following is the code:我面临运算符重载的问题,当我编译我的程序时,它给了我一个错误,以下是代码:

class box
{
    int length;
    int width;
    int volume;
public:
    box():length(50),width(30)
    {

    }

    box& operator++()
    {
         volume++;
         width++;
         length++;
    }
};

int main()
{
    box b1;

    cout<<++b1;
}

The error it gives me is:它给我的错误是:

"no match for operator <<" “不匹配运算符<<”

My question is why does the compiler give me an error although my syntax seems good?我的问题是为什么编译器给我一个错误,尽管我的语法看起来不错?

Two problems:两个问题:

  1. Return *this from your overloaded operator.从您的重载运算符返回 *this。

  2. If you want to print your object using "cout << ", you need to overload operator <<, otherwise print each member individually.如果要使用“cout <<”打印对象,则需要重载运算符 <<,否则单独打印每个成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将增量运算符应用于常量变量时​​,为什么会出现编译器错误 - Why do I get a compiler error, when applying the increment operator to a constant variable 为什么在使用指针时不要求运算符重载为“ &lt;”? - Why is my operator overload not called for “<” when I use pointers? 为什么我无法使用我的增量运算符重载? [C++] - Why am I unable to use my increment operator overload? [C++] 为什么编译器找不到这个运算符<< overload? - Why can't the compiler find this operator<< overload? 为什么C ++编译器在这个简单的程序中没有给出优先级(赋值下的递增运算符)? - Why the C++ compiler does not give precedence (increment operator under assignment) in this simple program? 当我尝试重载运算符时,为什么会出现链接错误? - Why am I getting a Link error when I try to overload an operator? 为什么我在 + 运算符重载函数返回的对象上重载 &lt;&lt; 时会出错 - Why do I get an error when I overload the << on the object returned by the + operator overloaded function 为什么重载运算符&amp;&amp;错误? - why overload operator&& error? 尝试为我的日期类重载运算符++。 仍然收到错误:无法递增类型“日期”的值 - trying to overload operator ++ for my date class. still getting the error: cannot increment value of type 'Date' 为什么我不能重载::运算符? - Why I cannot overload the :: operator?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM