摘要:运算符能给程序员提供一种书写数学公式的感觉,本质上运算符也是一种函数,因此有类内部运算符和全局运算符之分,通过重载,运算符的“动作”更加有针对性,编写代码更像写英文文章。
1、C++标准允许将运算符重载为类成员或者全局的,一般如果是全局的话,为了效率,都是把它们定义为类友元函数。
1 /* 2 ** 重载全局运算符“+”、“-”,代码如下: 3 */ 4 #include <iostream> 5 6 using namespace std; 7 8 //class Complex; 9 //Complex operator+(const Complex &c1, const Complex &c2); 10 //Complex operator-(const Complex &c1, const Complex &c2); 11 // 我的疑问:声明为全局的有什么好处的,或者说有什么必要的么? 12 class Complex 13 { 14 public: 15 Complex(double real = 0.0, double image = 0.0) 16 { 17 this->real = real; 18 this->image = image; 19 } 20 public: 21 void displayComplex() 22 { 23 if(image >= 0) 24 cout << "(" << real << '+' << image << 'i' << ")"; 25 else 26 cout << "(" << real << image << 'i' << ")"; 27 } 28 friend Complex operator+(const Complex &c1, const Complex &c2); 29 friend Complex operator-(const Complex &c1, const Complex &c2); 30 private: 31 double real; 32 double image; 33 }; 34 35 Complex operator+(const Complex &c1, const Complex &c2) 36 { 37 Complex complexTemp; 38 complexTemp.real = c1.real + c2.real; 39 complexTemp.image = c1.image + c2.image; 40 return complexTemp; 41 } 42 Complex operator-(const Complex &c1, const Complex &c2) 43 { 44 Complex complexTemp; 45 complexTemp.real = c1.real - c2.real; 46 complexTemp.image = c1.image - c2.image; 47 return complexTemp; 48 } 49 int main() 50 { 51 Complex c, c1(1.1, 2.2), c2(3.3, 4.4); 52 c = c1 + c2; 53 c = c1 - c2; // operator-(c1, c2); 54 c1.displayComplex(); 55 cout << "-"; 56 c2.displayComplex(); 57 cout << "="; 58 c.displayComplex(); 59 cout << endl; 60 61 int i; 62 cin >> i; 63 return 0; 64 }