c++ 筆記 | 第4課 操作符重載
文章目錄
二目操作符的成員函數
complex complex::operator+(complex c2) {return complex(r + c2.r, i + c2.i); }
// 或
complex complex::operator+(
const complex
&c2) { // 引用可以提高效率,const 修飾符可以確保引用方式不帶來副作用
return complex(r + c2.r, i + c2.i);
}
二目操作符的友元函數
// 類內
friend complex operator+(complex c1, complex c2);
// 類外
complex operator+(complex c1, complex c2) {return complex(c1.r + c2.r, c1.i + c2.i);
}
// 或
friend complex operator+(const complex &c1, const complex &c2) {return complex(c1.r + c2.r, c1.i + c2.i);
}
單目操作符的成員函數
// 前置單目運算符重載
void operator++(){ ++num_;}
// 後置單目運算符重載
void operator++(int) {num_++;}
單目操作符的友元函數
必須使用引用,否則無法改變相應對象的值
// 類內
friend void operator ++(Clock &c);
friend void operator ++(Clock &c, int);
// 類外
void operator ++(Clock &c) {++c.num_;}
void operator ++(Clock &c, int){c.num_++;}
特殊操作符的重載
// 類內
String &operator=(String str2);
// 類外: 對等號運算符進行重載, 從而進行地址的深複製 (類似自己實現的複製構造函數)
// 這種方式不支持 str2=str2 或 (str2=str1)=str2
String &String::operator=(String str2) {delete[] this->p;
this->p = new char[strlen(str2.p) + 1];
strcpy(this->p, str2.p);
return *this;
}
// 所以需要進一步改寫 = 操作符重載函數爲:
String &String::operator=(String &str2) {char *q = new char[strlen(str2.p) + 1]; // 先申請新內存 q
strcpy(q, str2.p); // 把 str2.p 所指字符串複製過去
delete[] this->p; // 刪除當前對象中 p 所指內存
this->p = q; // 讓當前對象中 p 指向新內存 q
return *this;
}
// 也可以寫爲
String &String::operator=(const String &str2) {if (&str2 != this) {delete[] this->p; // 刪除當前對象中 p 所指內存
this->p = new char[strlen(str2.p) + 1]; // 申請新內存
strcpy(this->p, str2.p); // 把 str2.p 所指字符串複製過去
}
return *this;
}
<< 操作符的重載
函數參數和返回值都必須是 I/O 對象的引用,而且只能將 <<
和 >>
重載爲類的友元函數
// 類內
friend ostream &operator<<(ostream &, complex &);
// 類外
ostream &operator<<(ostream &output, complex &c) {output << "(" << c.r_ << "," << c.i_ << ")" << endl;
return output;
}
類型操作符的重載 (double)
如果想把複數 complex
類對象 c 的實部當做普通 double
數進行運算,則需要 double(c)
— 類型轉換函數,把一個類的對象轉換成另一個類型的數據
類型轉換函數只能作爲相應類的成員函數
類型轉換函數要慎用 (因爲運算符優先級問題)
// 一般形式
operator 類型名 ( )
{return 與類型名類型相同的轉換結果;}
// 把複數 complex 類對象 c 的實部當做普通 double 數進行運算
operator double( ) // 類型轉換函數
{return r_;}
重載 ++,-- 操作符函數的返回值
// 重載爲成員函數
complex &complex::operator++() {
r++;
i++;
return *this; // 返回當前對象
}
complex complex::operator++(int) {
double rt = r, it = i;
r++;
i++;
return complex(rt, it);
}
// 重載爲友元函數
complex &operator++(complex &c) {
c.r++;
c.i++;
return c; // 返回所操作的 c 對象
}
complex operator++(complex &c, int k) {
double r = c.r, i = c.i;
c.r++;
c.i++;
return complex(r, i);
}