一、運算符重載
C++中預定義的運算符的操作對象只能是基本數據類型,實際上,對於很多用戶自定義類型,也需要有類似的運算操作。如果將C++中這些現存的運算符直接作用於用戶自定義的類型數據上,會得到什么樣的結果呢?編譯器無法給出正常的結果,因為我們需要運算符重載,給運算符賦予多重含義,使同一個運算符作用於不同類型的數據導致不同類型的行為,增強了運算符的普適性。
運算符重載的實質是函數重載。在實現過程中,首先把指定的運算表達式轉化為對運算符函數的調用,運算對象轉化為運算符函數的實參,然后根據實參的類型來確定需要調用達標函數,這個過程在編譯過程中完成。
運算符重載規則如下:
①、 C++中的運算符除了少數幾個之外,全部可以重載,而且只能重載C++中已有的運算符。
②、 重載之后運算符的優先級和結合性都不會改變。
③、 運算符重載是針對新類型數據的實際需要,對原有運算符進行適當的改造。一般來說,重載的功能應當與原有功能相類似,不能改變原運算符的操作對象個數,同時至少要有一個操作對象是自定義類型。
C++中只有五個運算符不能被重載,它們是:成員運算符“.”、指針運算符“*”、作用域運算符“::”、“sizeof”、條件運算符“?:”。
運算符重載形式有兩種,重載為類的成員函數和重載為類的友元函數。
運算符重載為類的成員函數的一般語法形式為:
函數類型 operator 運算符(形參表) { 函數體; }
運算符重載為類的友元函數的一般語法形式為:
1 friend 函數類型 operator 運算符(形參表) 2 { 3 函數體; 4 }
其中,函數類型就是運算結果類型;operator是定義運算符重載函數的關鍵字;運算符是重載的運算符名稱。
當運算符重載為類的成員函數時,函數的參數個數比原來的操作個數要少一個;當重載為類的友元函數時,參數個數與原操作數個數相同。原因是重載為類的成員函數時,如果某個對象使用重載了的成員函數,自身的數據可以直接訪問,就不需要再放在參數表中進行傳遞,少了的操作數就是該對象本身。而重載為友元函數時,友元函數對某個對象的數據進行操作,就必須通過該對象的名稱來進行,因此使用到的參數都要進行傳遞,操作數的個數就不會有變化。
運算符重載的主要優點就是允許改變使用於系統內部的運算符的操作方式,以適應用戶自定義類型的類似運算。
二、運算符重載程序例子(成員函數方式)
1 //運算符重載:成員函數方式 2 #include <iostream> 3 using namespace std; 4 5 class complex //復數類 6 { 7 public: 8 complex(){ real = imag = 0;} 9 complex(double r, double i) 10 { 11 real = r; 12 imag = i; 13 } 14 complex operator + (const complex &c); 15 complex operator - (const complex &c); 16 complex operator * (const complex &c); 17 complex operator / (const complex &c); 18 19 friend void print(const complex &c); //友元函數 20 21 private: 22 double real; //實部 23 double imag; //虛部 24 25 }; 26 27 inline complex complex::operator + (const complex &c) //定義為內聯函數,代碼復制,運算效率高 28 { 29 return complex(real + c.real, imag + c.imag); 30 } 31 32 inline complex complex::operator - (const complex &c) 33 { 34 return complex(real - c.real, imag - c.imag); 35 } 36 37 inline complex complex::operator * (const complex &c) 38 { 39 return complex(real * c.real - imag * c.imag, real * c.real + imag * c.imag); 40 } 41 42 inline complex complex::operator / (const complex &c) 43 { 44 return complex( (real * c.real + imag * c. imag) / (c.real * c.real + c.imag * c.imag), 45 (imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag) ); 46 } 47 48 void print(const complex &c) 49 { 50 if(c.imag < 0) 51 cout<<c.real<<c.imag<<'i'<<endl; 52 else 53 cout<<c.real<<'+'<<c.imag<<'i'<<endl; 54 } 55 56 int main() 57 { 58 complex c1(2.0, 3.5), c2(6.7, 9.8), c3; 59 c3 = c1 + c2; 60 cout<<"c1 + c2 = "; 61 print(c3); //友元函數不是成員函數,只能采用普通函數調用方式,不能通過類的對象調用 62 63 c3 = c1 - c2; 64 cout<<"c1 - c2 = "; 65 print(c3); 66 67 c3 = c1 * c2; 68 cout<<"c1 * c2 = "; 69 print(c3); 70 71 c3 = c1 / c2; 72 cout<<"c1 / c2 = "; 73 print(c3); 74 return 0; 75 }