Next, let's take a look at the example of the c ++ overload post-auto-addition operator. If you need to learn the C ++ auto-addition operator, you can refer to it.
The Code is as follows: |
Copy code |
# Include <iostream> Using namespace std; Class num { Public: Int x; Num () {n = 1; cout <"constructor execution! N ";} Num (int I) {n = I; cout <": run the constructor with parameters! N ";} Num (const num & s) {this-> n = s. n; cout <"copy constructor execution! N ";} ~ Num () {cout <"destructor execution! N ";} Int get () const {return n ;} Void set (int x) {n = x ;} Void add () {++ n;} // The error code returned when the custom addition function is incorrect: expected '; 'before': 'toke Const num & operator ++ () {// pre-auto-increment. The key to const is to prevent auto-increment after the return, that is, to avoid the appearance of ++ and so on, to avoid copying constructor calls by referencing '&', operator is the c ++ keyword function name, which is the same as the normal number of reloads. the type of the c ++ defined operator, the following ++ indicates that the auto-increment operator is reloaded, and the Implementation part is in {}. ++ N; Return * this; // * shis is the original object } Const num operator ++ (int o) {// post auto-addition. The function of parameter o is different from the preceding function. The key of const is to prevent auto-addition after return, that is to say, to avoid the appearance of ++ and the like, reference '&'. To avoid calling the copy constructor, operator is the c ++ keyword function name, which is the same as the normal number of reloads, the type of the defined operators in c ++. The following ++ indicates that the self-added operators are reloaded, and the Implementation part is in {}. Num tem (* this ); This-> n ++; // this-> can be omitted Return tem; } Private: Int n; }; Int main () { Num I; // I. add (); // call the member function to implement auto-Addition Num y = I ++; // post auto-Increment Cout <"I:" <I. get () <endl; // post-auto-added I member Value Cout <"y:" <y. get () <endl; // post-auto-added Member values of y // Y ++; this is wrong because I is an object and there is no auto-increment operation. Return 0; } |