Overloading postfix and prefix operators

consider the following code

#include <iostream>
using namespace std;
class Digit
{

private:
    int m_digit;
public:
    Digit(int ndigit=0){
     m_digit=ndigit;
                        }
    Digit& operator++();//prefix
    Digit& operator--();   //prefix
        Digit operator++(int);
        Digit operator--(int);
        int get() const { return m_digit;}
};
Digit& Digit::operator++(){

   ++m_digit;
   return *this;
}
Digit& Digit::operator--(){
 --m_digit;
 return *this;

}
Digit Digit::operator++(int){
Digit cresult(m_digit);
++(*this);
return cresult;


}
    Digit Digit::operator--(int){
Digit cresult(m_digit);
--(*this);
return cresult;


}
    int main(){

     Digit cDigit(5);
      ++cDigit;
        cDigit++;
         cout<<cDigit.get()<<endl;
         cout<<cDigit.get()<<endl;





     return 0;
    }

two versions of postfix and prefix operators are implemented here, I read that the difference is made by introducing another so-called dummy argument, but I have a question if we see an announcement of these

Digit& operator++();//prefix
             Digit& operator--();   //prefix
        Digit operator++(int);
        Digit operator--(int);

they differ in sign, so why do we need a dummy argument? and also in both cases, for example, the ++ operator is written before the argument and does it mean that they are the same?

+5
source share
4 answers

Pre- and post-increment are two different operators and require separate overloads.

++ , , , , .

- , ++ .

+9

, , . / .

operator++()
operator++(int)

, . Digit& Digit; - , ++ x x ++.

+2

++ / , . , , , , , ? .

int x = 2;

const int DoIt()
{
    return 1;
}

int& DoIt()
{
    return x;
}

int y = DoIt();

- , .

. http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.14

+2

Pre-Increment/Decrement Post-Increment/Decment

operator++()         => Prefix Increment
operator--()         => Prefix Decrement

operator++(int)      => Postfix Increment
operator--(int)      => Postfix Decrement

return type may be the same. You can also link: http://www.tutorialspoint.com/cplusplus/increment_decrement_operators_overloading.htm

+1
source

All Articles