有的時候程式中存在隱藏式轉換
比如下面這個例子
#include<iostream>using namespace std;class myComplex {private:int real; //複數的實部int image; //複數的虛部public:myComplex(int real = 0, int image = 0) {this->real = real;this->image = image;}friend bool operator == (const myComplex &obj1, const myComplex &obj2);};bool operator == (const myComplex &obj1, const myComplex &obj2) {if (obj1.real == obj2.real && obj1.image == obj2.image)return true;return false;}int main() {myComplex TestA(3,0);myComplex TestB(10,0);if (TestA == 3) {cout << "SAME" << endl;}else {cout << "NOT SAME" << endl;}system("PAUSE");return 0;
我們通過重載操作符 == 來判斷兩個自訂的類:複數是否相等
myComplex(int real = 0, int image = 0)
在建構函式中,我們給形參定義了預設值 所以在產生對象時 如果不指定形參 便會使用預設值
C++中,如果建構函式可以只傳入一個參數來調用,則會發生隱式轉換
if (TestA == 3)
在上面行代碼中 將3傳入重載操作符函數 建構函式便會構造一個3,0的myComplex對象, 這便發生了隱式轉換(將int型轉為myComplex型)
我們可以通過使用explicit來避免隱式轉換
explicit myComplex(int real = 0, int image = 0) {this->real = real;this->image = image;}
這時必須指明類型
myComplex TestA(3,0);myComplex TestB(10,0);if (TestA == (myComplex)3) { //必須指明類型cout << "SAME" << endl;}else {cout << "NOT SAME" << endl;}