1. Increment decrement operator
The C + + language does not require that the increment decrement operator be a member of a class. But because they change exactly the state of the object being manipulated. Therefore, it is recommended to set the member function .
For increment and decrement operators, there is a predecessor and a post two version number, so. We should define the increment and decrement operators for the two version numbers for a class.
Here's the problem. How does the program differentiate between front and rear? since all are + + and-in order to solve the problem, the increment decrement operator of the post version number accepts an additional (unused) int type of the form . When we use the post operator, the compiler provides an argument with a value of 0 for this shape.
The only function of this shape is to differentiate between pre-and post-operator functions.
Because int is not used, it is not required to be named.
Examples include the following:
Person & person::operator++ ()//++{age++;//only + + Agereturn *this of the predecessor version number;} Person & person::operator--()//--{age--;return *this of the predecessor version number;} Person & person::operator++ (int)//++{person of the post version number &p = *this;age++;return p;} Person & person::operator--(int)//--{person of the post version number &p = *this;age--;return p;}
int main () {person P1 ("SCOTT"); Person P2 ("Kate"), cout << p1 << endl;p1--;cout << p1 << endl;return 0;}
The above code is relatively simple, in order to facilitate the demonstration. In our person, only the age member variable in the person class is incremented and decremented.
Execution Result:
Init person
Init person
P.AGE:20, P.name:scott
P.age:19, P.name:scott
~person name:0x8dcc048 Age:10
~person name:0x8dcc020 age:19
2. Member access operator
The dereference operator (*) and Arrow operators (-) are often seen in iterator classes and smart pointer classes.
We are also able to define these two operators ourselves.
Examples:
Person * person::operator-> () {return this;}
Person & person::operator* () {return *this;}
int main () {person P1 ("SCOTT"); Person P2 ("Kate"), cout << p1->getname () << endl;cout << (*P2). GetName () << Endl;return 0;}
Execution Result:
Init person
Init person
SCOTT
Kate
~person name:0x89d7048 Age:10
~person name:0x89d7020 age:20
C + + Primer Note 12_ operator overload _ Increment Decrement Operator _ member access operator