在C++中,系統已經對左移運算符“<<”和右移運算符“>>”分別進行了重載,使其能夠用於輸入輸出,但是輸入輸出的處理對象只能是系統內建的數據類型。系統重載這兩個運算符是以系統類成員函數的形式進行的,因此cout<< var
語句可以理解為:
cout.operator<<( var )
如果我們自己定義了一種新的數據類型,需要用輸入輸出運算符去處理,那么就要重載。本節以前面的 complex 類為例說明輸入輸出運算符的重載。
重載輸入運算符>>
下面我們用全局函數的形式重載輸入運算符,使它能夠讀入兩個 double 類型的數據,並轉換為一個復數,保存到復數對象中:
istream & operator>>(istream & in, complex & A){ in >> A.real >> A.imag; return in; }
istream 是輸入流,cin 就是 istream 類的對象,后續會講解。因為重載運算符函數需要用到 complex 類的 private 成員變量,為了方便,我們將這個函數聲明為 complex 類的友元函數。聲明形式如下:
friend istream & operator>>(istream & in , complex & a);
該函數可以按照如下方式使用:
complex c;
cin>> c;
當輸入1.45 2.34↙
后,這兩個小數就分別成為 complex 對象 c 的實部和虛部了。cin>> c;
這一語句其實可以理解為:
operator<<(cin , c);
在重載輸入運算符時,采用引用的方式進行參數傳遞:輸入的參數里面包含一個 istream 類的引用,返回值仍然為該引用。這樣做的一個明顯好處就是可以采用鏈式輸入(也就是連續輸入),如下所示:
complex c1, c2, c3;
cin>> c1 >> c2 >> c3;
重載輸出運算符<<
同樣的,我們也可以模仿上面的方式對輸出運算符進行重載,讓它能夠輸出復數。函數在類內部的聲明如下:
rriend ostream &(ostream & out, complex & A);
全局函數的實現如下:
ostream & operator<<(ostream & out, complex & A){ out << A.real <<" + "<< A.imag <<" i "; return out; }
與 istream 相反,ostream 表示輸出流,cout 就是 ostream 類的對象。為了能夠直接訪問 complex 類的私有成員變量,同樣需要將這個函數聲明為 complex 類的友元函數。由於采用了引用的方式進行參數傳遞,該輸出運算符重載函數可以實現鏈式輸出。
結合輸入輸出運算符的重載,重新實現 complex 類:
#include <iostream> using namespace std; class complex{ private: double real; //復數的實部 double imag; //復數的虛部 public: complex(): real(0.0), imag(0.0){ }; complex(double a, double b): real(a), imag(b){ }; friend complex operator+(const complex & A, const complex & B); friend complex operator-(const complex & A, const complex & B); friend complex operator*(const complex & A, const complex & B); friend complex operator/(const complex & A, const complex & B); friend istream & operator>>(istream & in, complex & A); friend ostream & operator<<(ostream & out, complex & A); }; //重載加法運算符 complex operator+(const complex & A, const complex &B){ complex C; C.real = A.real + B.real; C.imag = A.imag + B.imag; return C; } //重載減法運算符 complex operator-(const complex & A, const complex &B){ complex C; C.real = A.real - B.real; C.imag = A.imag - B.imag; return C; } //重載乘法運算符 complex operator*(const complex & A, const complex &B){ complex C; C.real = A.real * B.real - A.imag * B.imag; C.imag = A.imag * B.real + A.real * B.imag; return C; } //重載除法運算符 complex operator/(const complex & A, const complex & B){ complex C; double square = A.real * A.real + A.imag * A.imag; C.real = (A.real * B.real + A.imag * B.imag)/square; C.imag = (A.imag * B.real - A.real * B.imag)/square; return C; } //重載輸入運算符 istream & operator>>(istream & in, complex & A){ in >> A.real >> A.imag; return in; } //重載輸出運算符 ostream & operator<<(ostream & out, complex & A){ out << A.real <<" + "<< A.imag <<" i ";; return out; } int main(){ complex c1, c2, c3; cin>>c1>>c2; c3 = c1 + c2; cout<<"c1 + c2 = "<<c3<<endl; c3 = c1 - c2; cout<<"c1 - c2 = "<<c3<<endl; c3 = c1 * c2; cout<<"c1 * c2 = "<<c3<<endl; c3 = c1 / c2; cout<<"c1 / c2 = "<<c3<<endl; return 0; }
在本例中,我們均采用全局函數的形式進行運算符重載,這樣在輸入輸出時方便了不少。