1 知識點
- 課程來自B站侯捷老師視訊
- 好習慣是使用使用防衛式聲明,避免重複定義類
- 構造函數初始化清單
- 傳參和傳回類型盡量使用reference(引用)
- 類成員函數不改變輸入參數則盡量使用const
- 二進制操作符重載,預設由this傳入第一個參數
- 由類構造函數生成臨時對象
- 不能傳回局部對象的引用
- cout的重載用到ostream&作為傳回類型
- 友元函數可以類外進行重載,可以通路類中的private成員
- 内聯函數的類外定義
2 代碼
#include <iostream>
using namespace std;
#ifndef __complex__ // 防衛式聲明
#define __complex__
class complex{
public:
complex(double r = 0, double i = 0)
:re(r), im(i){} // 構造函數初始化清單
complex& operator += (const complex&);
double real() const {return re;} // 類成員函數不改變輸入參數則盡量使用const
double imag() const {return im;}
//二進制運算符用成員重載時, 隻需要一個參數,另一個參數由this指針傳入
complex operator + (const complex& y){
return complex(this->real()+y.re, this->imag()+y.im);
}
private:
double re, im;
friend complex& __doapl (complex*, const complex&); // 友元函數
};
inline complex& complex::operator += (const complex& r){ //内聯函數
return __doapl (this, r);
}
inline complex& __doapl (complex*ths, const complex& r){ // 友元函數類外定義
ths->re += r.re;
ths->im += r.im;
return *ths;
}
ostream& operator << (ostream& os, const complex& x){
return os << '(' << x.real() << ',' << x.imag() << ')' ;
}
#endif
int main(){
complex c1(2,3);
complex c2(1,1);
complex c3;
c1 += c2;
c3 = c1 + c2;
cout << c1.real() << endl;
cout << c1.imag() << endl;
cout << c3 << endl;
return 0;
}
3 程式輸出
3
4
(4,5)