Wednesday, September 18, 2019

c++ - Return value of operator++




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 
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<
return 0;
}


Answer



You attempt to apply the second ++ to the temporary object returned by the first invocation. However, the operand must be passed by reference, and you can't bind a temporary to a non-constant lvalue reference.



You probably don't want to "fix" this, since there's little reason to modify a temporary value like that. However, you should return a copy of the value before incrementing it, to give the expected post-increment behaviour.



The prefix operator should return a reference, which can be happily bound to another reference so that ++++x; should work as expected.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...