In general, an operator whose result is a new value (such as +, -, etc) must return the new value by value, and an operator whose result is an existing value, but modified (such as <<, >>, +=, -=, etc), should return a reference to the modified value.
Each of the operators yields 1 if the specified relation is true and 0 if it is false.
The inner operator++ call returns a temporary Number object. The outer operator++() expects a parameter of type Number& - but a non-const reference can't bind to a temporary.
The & in the Poly& Poly::operator= declaration means that the operator returns a reference - to itself in this case, which is precisely what return *this; does. On the other hand, the & in &p1 evaluates to the address of p1 , which is a Poly* pointer, and cannot be assigned to a Poly object.
I have the following code that is broken. I can fix it by modifying certain line in code (see the comment). What is the cause of the problem?
#include <iostream>
using namespace std;
class Number{
public:
int n;
Number(int a):n(a){}
//when I change the following to
//friend Number& operator++(Number& source, int i)
//then it compiles fine and correct value is printed
friend Number operator++(Number& source, int i){
++source.n;
return source;
}
};
int main() {
Number x(5);
x++++; //error: no 'operator++(int)' declared for postfix '++' [-fpermissive]
cout<<x.n;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With