<<
和右移運算符>>
分別進行了重載,使其能夠用於不同數據的輸入輸出,但是輸入輸出的對象只能是 C++ 自帶的數據類型,包括 int、float、bool 等基本類型,以及 string、complex 等標准庫自定義的類型(也就是類)。其實 C++ 標准庫已經提供了 complex 類,能夠很好地支持復數運算,但是這裡我們又自己定義了一個 complex 類,這樣做僅僅是為了教學演示。本節要達到的目標是讓復數的輸入輸出和 int、float 等基本類型一樣簡單。假設 num1、num2 是復數,那麼輸出形式就是:
cout<<num1<<num2<<endl;
輸入形式就是:cin>>num1>>num2;
要想達到這個目標,就必須以全局函數的形式重載<<
和>>
。>>
,使它能夠讀入兩個 double 類型的數據,並轉換為一個復數,保存到復數對象中:istream & operator>>(istream &in, complex &A){ in >> A.m_real >> A.m_imag; return in; }istream 表示輸入流,cin 是 istream 類的對象,只不過這個對象是在標准庫中定義的。之所以返回 istream 類對象的引用,是為了能夠連續讀取復數,讓代碼書寫更加漂亮,例如:
cin>>num1>>num2;
如果不返回引用,那就只能一個一個地讀取了:
cin>>num1;
cin>>num2;
friend istream & operator>>(istream & in , complex &a);
>>
運算符可以按照下面的方式使用:
complex c;
cin>>c;
1.45 2.34↙
後,這兩個小數就分別成為對象 c 的實部和虛部了。cin>> c;
這一語句其實可以理解為:
operator<<(cin , c);
ostream & operator<<(ostream &out, complex &A){ out << A.m_real <<" + "<< A.m_imag <<" i "; return out; }ostream 表示輸出流,cout 是 ostream 類的對象。由於采用了引用的方式進行參數傳遞,並且也返回了對象的引用,所以重載後的運算符可以實現連續輸出。
friend ostream & operator<<(ostream &out, complex &A);
#include <iostream> using namespace std; class complex{ public: complex(): m_real(0.0), m_imag(0.0){ }; complex(double a, double b): m_real(a), m_imag(b){ }; public: 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); private: double m_real; //實部 double m_imag; //虛部 }; //重載加法運算符 complex operator+(const complex & A, const complex &B){ complex C; C.m_real = A.m_real + B.m_real; C.m_imag = A.m_imag + B.m_imag; return C; } //重載減法運算符 complex operator-(const complex & A, const complex &B){ complex C; C.m_real = A.m_real - B.m_real; C.m_imag = A.m_imag - B.m_imag; return C; } //重載乘法運算符 complex operator*(const complex & A, const complex &B){ complex C; C.m_real = A.m_real * B.m_real - A.m_imag * B.m_imag; C.m_imag = A.m_imag * B.m_real + A.m_real * B.m_imag; return C; } //重載除法運算符 complex operator/(const complex & A, const complex & B){ complex C; double square = A.m_real * A.m_real + A.m_imag * A.m_imag; C.m_real = (A.m_real * B.m_real + A.m_imag * B.m_imag)/square; C.m_imag = (A.m_imag * B.m_real - A.m_real * B.m_imag)/square; return C; } //重載輸入運算符 istream & operator>>(istream & in, complex & A){ in >> A.m_real >> A.m_imag; return in; } //重載輸出運算符 ostream & operator<<(ostream & out, complex & A){ out << A.m_real <<" + "<< A.m_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; }運行結果: