为什么“cout << ++Object;" produce an error? (Both << and ++ have been overloaded)

问题描述 投票:0回答:1

在下面的代码中,

<<
++
运算符都被重载了:

#include <iostream>
using namespace std;

class Test{
public:
    int num=0;
    Test operator++(){
      num++;
      return *this;
    }
};

ostream &operator<<(ostream &mystream, Test &x){
    mystream << x.num;
    return mystream;
}

当我在 main() 中增加 num 的值时,在 cout

 之前使用表达式
++a;,代码执行得很好:

int main(){
    Test a;
    ++a;
    cout << a << endl;
    return 0;
}

但是,当我尝试增加 num 的值时,

<<
运算符之后

int main(){
    Test a;
    cout << ++a << endl;
    return 0;
}

每次运行代码都会产生以下错误:

error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Test')
    cout << ++a << endl;
    ~~~~ ^  ~~~

为什么会发生这种情况,我该怎么办?

c++ class operator-overloading
1个回答
0
投票

你的类中定义的前缀运算符++

Test operator++(){
  num++;
  return *this;
}

返回类型为 Test 的临时对象。

但是重载运算符<< expects an lvalue reference to an object of the class

ostream &operator<<(ostream &mystream, Test &x){
    mystream << x.num;
    return mystream;
}

您不能将左值引用绑定到临时对象。

例如,您可以将运算符 ++ 定义为以下方式(并且应该以这种方式定义)

Test & operator++(){
  num++;
  return *this;
}

或/并定义运算符<< the following way

ostream &operator<<(ostream &mystream, const Test &x){
    mystream << x.num;
    return mystream;
}

提供可以绑定到临时对象的常量左值引用,

© www.soinside.com 2019 - 2024. All rights reserved.