Article From:https://segmentfault.com/q/1010000011097066
Question:
 #include <iostream>
 using namespace std;
 struct Date
 {
    void  operator++()
    {
      cout << "oprator++()" <<endl;
    }
    void  operator++(int) 
    {
      cout << "oprator++(int)" <<endl;
    }
};
int main()
{
    Date  date;
    ++date;  
    date++;
}

Why does ++date correspond to + + () rather than + + (int)?
And then why + + (int) can only be int, try float and Date are not good, I clearly use the Date object for ++ operations ah

Answer 0:

Since the + + operator itself does not accept any parameters either in front or in the post, if no intervention is done, both prepositions and postpositions are the same.

void operator++();

This is definitely not acceptable. The overloading of pre and post operators should be separated.
So C++ specifies that the post operator overloading takes a int as a parameter (but it doesn’t work):

void operator++(int);

This can be divided into two overloads.
Do not ask why this is int, nothing else, because that is the rule.

Answer 1:

Operator overloading is defined by the method of the class in the same way as the method of the class: function name, number of parameters, parameter type to be consistent.

void operator++(int){}//Accept a int parameter and do not return the value./So it must be a int

Answer 2:

This is a requirement for the compiler to differentiate in what way, and there is no logic, just a rule..
If I define this rule, I will probably distinguish in the following way:
void operator front++();
void operator back++();

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *