Overloading Postfix Operator ++

I overloaded the prefix version of the ++ operator. How can I overload the postfix version if the overloaded function is NOT a member of my class *?

#include <iostream> using namespace std; class Number{ int number; public: Number(int inNr):number(inNr){} friend void operator++(Number& fst); }; void operator++(Number& fst){ fst.number=fst.number+1; } int main(){ Number nr1(1); ++nr1; //nr1++; error: no 'operator++(int)' declared for postfix '++' } 

* I understand that if he is a member of a class, I can use the dummy int parameter to distinguish them.

+4
source share
2 answers

Non-member overloads also use the dummy int parameter to distinguish them:

 friend void operator++(Number&); // prefix friend void operator++(Number&, int); // postfix 

Please note that some people may expect that they emulate the behavior of an inline operator, returning new and old values ​​respectively:

 Number& operator++(Number& fst) { fst.number=fst.number+1; return fst; // reference to new value } Number operator++(Number& fst, int) { Number old = fst; ++fst; return old; // copy of old value } 
+12
source

I believe (I cannot verify this at the moment), you use a dummy int as the second parameter to overload the statement, i.e.

 void operator++(Number& fst, int /*dummy*/){ fst.number=fst.number+1; } 
+1
source

Source: https://habr.com/ru/post/1493713/


All Articles