+
號可以對不同類型(int、float 等)的數據進行加法操作;<<
既是位移運算符,又可以配合 cout 向控制台輸出數據。C++ 本身已經對這些運算符進行了重載。+
號實現復數的加法運算:
#include <iostream> using namespace std; class complex{ public: complex(); complex(double real, double imag); public: //聲明運算符重載 complex operator+(const complex &A) const; void display() const; private: double m_real; //實部 double m_imag; //虛部 }; complex::complex(): m_real(0.0), m_imag(0.0){ } complex::complex(double real, double imag): m_real(real), m_imag(imag){ } //實現運算符重載 complex complex::operator+(const complex &A) const{ complex B; B.m_real = this->m_real + A.m_real; B.m_imag = this->m_imag + A.m_imag; return B; } void complex::display() const{ cout<<m_real<<" + "<<m_imag<<"i"<<endl; } int main(){ complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display(); return 0; }運行結果:
operator
是關鍵字,專門用於定義重載運算符的函數。我們可以將operator 運算符名稱
這一部分看做函數名,對於上面的代碼,函數名就是operator+
。+
,該重載只對 complex 對象有效。當執行c3 = c1 + c2;
語句時,編譯器檢測到+
號左邊(+
號具有左結合性,所以先檢測左邊)是一個 complex 對象,就會調用成員函數operator+()
,也就是轉換為下面的形式:
c3 = c1.operator+(c2);
c1 是要調用函數的對象,c2 是函數的實參。complex complex::operator+(const complex &A)const{ return complex(this->m_real + A.m_real, this->m_imag + A.m_imag); }return 語句中的
complex(this->m_real + A.m_real, this->m_imag + A.m_imag)
會創建一個臨時對象,這個對象沒有名稱,是一個匿名對象。在創建臨時對象過程中調用構造函數,return 語句將該臨時對象作為函數返回值。
+
,實現復數的加法運算:
#include <iostream> using namespace std; class complex{ public: complex(); complex(double real, double imag); public: void display() const; //聲明為友元函數 friend complex operator+(const complex &A, const complex &B); private: double m_real; double m_imag; }; complex operator+(const complex &A, const complex &B); complex::complex(): m_real(0.0), m_imag(0.0){ } complex::complex(double real, double imag): m_real(real), m_imag(imag){ } void complex::display() const{ cout<<m_real<<" + "<<m_imag<<"i"<<endl; } //在全局范圍內重載+ 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; } int main(){ complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display(); return 0; }運算符重載函數不是 complex 類的成員函數,但是卻用到了 complex 類的 private 成員變量,所以必須在 complex 類中將該函數聲明為友元函數。
c3 = c1 + c2;
語句時,編譯器檢測到+
號兩邊都是 complex 對象,就會轉換為類似下面的函數調用:
c3 = operator+(c1, c2);