1. Operator overloading
- Assigning multiple meanings to an existing operator
- Produce different types of behavior when the same operator is acting on different types of data
Objective
- Extends the scope of the operators provided in C + + for use in the abstract data types represented by the class
The overloaded nature of an operator is a function overload with the following type:
operator operator (formal parameter list) { ... }
At program compile time
- Call to operator function with an expression that contains an operator
- Take the operand of an operator as an argument to an operator function
- Operator is overloaded multiple times, which operator function is called based on the type of the argument
- Operators can be overloaded into normal functions, or they can be overloaded into class member functions
Operator overloading is an example of a normal function:
#include <iostream>using namespacestd;classComplex { Public: Complex (DoubleR =0.0,Doublei =0.0) {Real=R; IMG=i; } DoubleReal//Real part Doubleimg//Imaginary part}; Complexoperator+ (ConstComplex &a,ConstComplex &b) { returnComplex (A.real+b.real, a.img+b.img);}intMain () {Complex A (1,2), B (2,3), C; C= A +b; cout<< C.real <<":"<< c.img <<Endl;}
Here a+b is equivalent to operator+ (A, b);
When overloading as a normal function, the number of arguments is the count of operators.
Operator overloading is an example of a member function: (when overloaded to a member function, the number of arguments is one less operator)
#include <iostream>using namespacestd;classComplex { Public: Complex (DoubleR =0.0,Doublei =0.0) {Real=R; IMG=i; } Complexoperator+(ConstComplex &);//additionComplexoperator-(ConstComplex &);//Subtraction DoubleReal//Real part Doubleimg//Imaginary part}; Complex Complex::operator+(ConstComplex &Operand2) { returnComplex (Real+operand2.real, img+operand2.img);} Complex Complex::operator-(ConstComplex &Operand2) { returnComplex (Real-operand2.real, img-operand2.img);}intMain () {Complex A (1,2), B (2,3), C; C= A +b; cout<< C.real <<":"<< c.img <<Endl; C= B-A; cout<< C.real <<":"<< c.img <<Endl;}
C + + operator overloading