In the code below, both << and ++ operators have been overloaded:
#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;
}
When I increase the value of num inside the main(), using the expression ++a; before cout, the code executes completely fine:
int main(){
Test a;
++a;
cout << a << endl;
return 0;
}
However, when I try to increase the value of num, after the << operator:
int main(){
Test a;
cout << ++a << endl;
return 0;
}
The following error is being produced each time I run the code:
error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Test')
cout << ++a << endl;
~~~~ ^ ~~~
Why does this happen and what could I do about this?
The prefix
operator++defined in your class:returns a temporary object of the type
Test.However, the overloaded
operator<<expects an lvalue reference to an object of the class:You cannot bind an lvalue reference to a temporary object.
You could, for example, either define the
operator++in the following way (and it should be defined that way):Or/and define the
operator<<in the following way:providing a constant lvalue reference that can bind to a temporary object.