C ++ programming and development operator overload parsing, programming and development Operator
C ++ programming and development operator overload parsing.
????? ? Now we have a class called shopping cart (SC ). If you don't have any functions, you just need to make it simple: the total cost of an output.
. Then I have an iPad Air 2 in my car.
# Include
Using namespace std; class SC {int price; public: SC (int p = 0) {price = p ;}~ SC () {} void show () {cout <
????? ? Now I want to add something to the car and add a summation function in the class.
int add(SC a){price += a.price;return price;}
????? ? To avoid adding and parentheses during use, reload the + operator and change add to operator +.
int operator+(SC a){price += a.price;return price;}
????? ? Now you can directly use SC1 + SC2.
????? ? The operator + function is a member function of the class.
????? ? Below, if I think an ipad is not enough, I want to buy one for my family and add a multiplication function.
int operator*(int n){return price*n;}
????? ? Now, cout <
The left operand must be the call object, but in general sense, iPadAir2 * 3 and 3 * iPadAir2 should be equivalent, and the UFIDA function can solve this problem well.
friend int operator*(int n,SC &a){a = a*n;return a.price;}
????? ? The membership function of the class is a non-member function, but its access permission is the same as that of the member function.
???????? Youyuan is often used to overload the <operator to facilitate class output with cout. If you do not use youyuan, use the member function to overload <Replace the show function,
The function code is as follows:
Void operator <(ostream & c) {cout <
????? ? This is because the call object must be the left operand, so iPadAir2 must be written for use. <
????? ? The expected results can be achieved by reversing the sequence of operands:
Friend void operator <(ostream & c, SC a) {cout <????? ? A problem still exists: the number of outputs cannot be multiple at a time, that is, the cout cannot be <
????? ? Now let's take a look at <operator definition: The left side must be an ostream object, such as cout <1; this is obviously true. We all know that,
????? ? Cout <1 <2; is feasible, which means that the <cout <1 on the left of the operator before 2 is an ostream object.
Change the return type of the operator <() function to reference the ostream object.
Friend ostream & operator <(ostream & c, SC a) {cout <????? ? Go to bed, and watch again tomorrow.
????????
????????
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?