Overload Operator ++

I am trying to deal with operator overloading for the first time, and I wrote this code to overload the ++ operator in order to increase class and i variables by one. It does the job, but the compiler showed these warnings:

Warning 1 warning C4620: there is no postfix form 'operator ++' found for type 'tclass' using the prefix form c: \ users \ ahmed \ desktop \ cppq \ cppq \ cppq.cpp 25

Warning Warning 2 C4620: there is no postfix form 'operator ++' found for type 'tclass' using the prefix form c: \ users \ ahmed \ desktop \ cppq \ cppq \ cppq.cpp 26

This is my code:

 class tclass{ public: int i,x; tclass(int dd,int d){ i=dd; x=d; } tclass operator++(){ i++; x++; return *this; } }; int main() { tclass rr(3,3); rr++; rr++; cout<<rr.x<<" "<<rr.i<<endl; system("pause"); return 0; } 
+4
source share
3 answers

This syntax is:

 tclass operator++() 

for the ++ prefix (which is actually usually written as tclass &operator++() ). To distinguish the postfix increment, you add an unused int argument:

 tclass operator++(int) 

Also note that prefix incrementing returns tclass & better , because the result can be used after: (++rr).x .

Again, note that the postfix increment is as follows:

 tclass operator++(int) { tclass temp = *this; ++*this; // calls prefix operator ++ // or alternatively ::operator++(); it ++*this weirds you out!! return temp; } 
+11
source

There are two ++ operator s. You have identified one and used the other.

 tclass& operator++(); //prototype for ++r; tclass operator++(int); //prototype for r++; 
+6
source

There are separate overloads for post-increment and pre-increment. The signature of the postincrement operator++(int) version, and the preincrement signature is operator++() .

You defined operator++() , so you only defined a preincrement. However, you are using postincrement for an instance of your class, so the compiler tells you that it will use the preincrement function call because postincrement is not specified.

+5
source

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


All Articles