標籤:this friend ret 需要 語言 有一個 c++語言 void 學習
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
接下來的幾篇文章,我將回憶一下C++的基礎.
C++的由兩部分組成 1.C++語言 2.C++標準庫 本篇文章主要分享我學習C++語言的筆記.
這次主要回憶一下操作符重載.
先看一段代碼,後續我會介紹這麼做的原由
#include <iostream>class complex{public: complex(double r = 0, double i = 0) : re(r) ,im(i) {} complex& operator += (const complex& r); double real() const { return re; } double imag() const { return im; } void real(double r); private: double re,im; friend complex& __doapl (complex*, const complex&);};inline doubleimag(const complex& x){ return x.imag ();}inline doublereal(const complex& x){ return x.real ();}
知識點1.重載成員函數
inline complex&complex::operator += (const complex& r){ return __doapl (this, r);}
C++的調用都是從左面開始,下面調用
complex c1(1,2);complex c2(2,3);c1 += c2;
例如c1 += c2 他的完整含義應該是 c1 調用了 +=這個函數 傳遞的參數是兩個其中一個是this(c1),另一個參數就是右邊的值了(c2),[在編譯器裡別這樣寫,編譯會報錯]
//認識成員函數都有一個this point 指向調用者//+=的完整形式應該是這樣,誰調用這個函數誰就是thisinline complex&complex::operator+=(this,const complex& r){ return __dopal(this, r);}
知識點2 . return by value, return by reference
//2.return by referenceinline complex& //引用接收 提高效率 還有一個重要的知識點 以備調用者 調用c3 += c2 += c1;__doapl(complex* ths, const complex& r){ ths->re += r.re; ths->im += r.im; return *ths; //返回的是對象, 接收卻是引用, 這是C++的一個重要知識點,傳遞著無需知道接收者以什麼形式接收}
為什麼 用引用接收 就可以讓調用者調用c3 += c2 += c1;
如果你不用引用接收那麼你第一次調用即c3 += c2時返回的即將是一個臨時變數,那麼在次調用c1時 c3 += c2 將毫無意義
知識點3 重載非成員函數
//3. 操作符重載 非成員函數 無thisinline complexoperator + (const complex& x, const complex& y){ return complex (real (x) + real (y), imag (x) + imag (y));}inline complexoperator + (const complex& x, double y){ return complex (real (x) + y, imag (x));}inline complexoperator + (double x, const complex& y){ return complex (x + real (y), imag (y));}
臨時對象:typename() 建立臨時對象 為什麼上面的三個傳回值不是reference 因為他們返回的一定是局部變數
知識點2.是左邊 = 左邊+ 右邊 左邊是一直存在的
知識點4 重載操作符
//<< 重載 由於這個操作符不認識我們新建立的對象我們需要重載//千萬不要把這個操作符寫成成員函數 必須寫成全域的std::ostream&operator << (std::ostream& os, const complex& x) //這裡的os就是cout 其實cout是一個類 別用const修飾 傳引用為了能夠相應連續調用{ return os << ‘(‘ << real (x) << ‘,‘ << imag (x) << ‘)‘;}
總結
1.傳遞著無需知道接收者以什麼形式接收
2.接收者(傳回值)是 by value還是 by reference, by value 一般返回臨時變數和將建立出的對象 , by reference 一般是在已經存在的對象上做修改
3.操作符重載不要加const ,不要聲明稱成員函數
如有不正確的地方請指正
參照<<侯捷 C++物件導向進階編程>>
C++物件導向進階編程(二)