运算符重载
运算符重载分为类的成员运算符重载和非成员运算符重载;
类内成员运算符重载:
语法:
双目运算符重载:
类名 operator运算符 (const 类名&);操作符的左操作数就是当前的对象,右操作数就是参数中的对象;
单目运算符重载:
自增自减运算符++、--;
①++或--在对象前面的情况:
类名& operator++ ();---这种情况下的重载没有参数;
②++或者--在对象的后面的情况:
类名 operator++ (int);----这种情况下给重载操作符函数提供一个参数只是为了说明运算符在对象的后面;
举例:
双目运算符:

单目运算符:

非成员运算符重载:
语法类似,不过,参数列表为成员从左到右的顺序,其中++和--的后置运算符例外,需额外加一个参数;
1 class Complex 2 { 3 double real; 4 double imag; 5 public: 6 Complex(double i = 0, double j = 0) : real(i), imag(j) {} 7 friend Complex operator+ (const Complex& c1, const Complex& c2); 8 friend Complex operator- (const Complex& c1, const Complex& c2); 9 friend ostream& operator << (ostream& out, const Complex& complex); 10 friend Complex& operator++ (Complex& c1); 11 friend Complex operator++ (Complex& c1, int); 12 }; 13 14 Complex operator + (const Complex& c1, const Complex& c2) 15 { 16 return Complex(c1.real + c2.real, c1.imag + c2.imag); 17 } 18 19 Complex operator - (const Complex& c1, const Complex& c2) 20 { 21 return Complex(c1.real - c2.real, c1.imag - c2.imag); 22 } 23 24 25 ostream& operator << (ostream& out, const Complex& complex) 26 { 27 out << complex.real << ", " << complex.imag << endl; 28 return out; 29 } 30 31 //++i 32 Complex& operator++ (Complex& c1) 33 { 34 c1.real++; 35 c1.imag++; 36 return c1; 37 } 38 39 //i++ 40 Complex operator++ (Complex& c1, int) 41 { 42 Complex complex; 43 complex = c1; 44 c1.real++; 45 c1.imag++; 46 return complex; 47 } 48 49 50 int main() 51 { 52 Complex complex1(2.0, 3.0), complex2(4, 5), complex3; 53 54 cout << complex1 << complex2 << complex3; 55 56 complex3 = complex1 + complex2; 57 cout << complex3; 58 59 complex3 = complex1 - complex2; 60 cout << complex3; 61 62 cout << ++complex3; 63 cout << complex3++; 64 65 cout << complex3; 66 67 68 return EXIT_SUCCESS; 69 }
声明为友元函数仅仅为了能够直接操作类的私有成员;
结果如下:

与预期相符;

浙公网安备 33010602011771号