C++中類類型的隱式轉(zhuǎn)換

C++中類類型的隱式轉(zhuǎn)換示例
<pre>#include <iostream>
class A{
public:
A() :a(0){} //默認(rèn)構(gòu)造函數(shù)
A(int i) :a(i){} //自定義構(gòu)造函數(shù)
void print(){ std::cout << a << std::endl; }
private:
int a;
};

int main(){
A b = true; //隱式轉(zhuǎn)換并執(zhí)行拷貝初始化,布爾值轉(zhuǎn)換為類類型A的一個(gè)實(shí)例,調(diào)用了自定義構(gòu)造函數(shù)
b.print();
return 0;
}</pre>注:C++中類類型的隱式轉(zhuǎn)換只支持一步轉(zhuǎn)換,以上代碼只執(zhí)行了一次轉(zhuǎn)換,即將布爾值轉(zhuǎn)換為int值帶入自定義構(gòu)造函數(shù)。

如下面的示例所示

<pre>#include <iostream>

include <string>

class A{
public:
A() :str(0){} //默認(rèn)構(gòu)造函數(shù)
A(std::string s) :str(s){} //自定義構(gòu)造函數(shù)
void print(){ std::cout << str << std::endl; }
A& add(const A &a){ str += a.str; return *this; }
private:
std::string str;
};

int main(){
A b = "hello"; //隱式轉(zhuǎn)換
b.add(" world"); //錯(cuò)誤,執(zhí)行了兩次轉(zhuǎn)換,應(yīng)改為b.add(std::string(" world"))
b.print(); //輸出 hello world
return 0;
}</pre>

下面的示例展現(xiàn)了一個(gè)有趣的現(xiàn)象

<pre>#include <iostream>
class A{
public:
A() :a(0){} //默認(rèn)構(gòu)造函數(shù)
//A(int i) :a(i){}
void print(){ std::cout << a << std::endl; }
A& operator=(int i){ a = i; return *this; } //拷貝賦值函數(shù)
private:
int a;
};

int main(){
A b = 2; //失敗,不存在適當(dāng)?shù)臉?gòu)造函數(shù)進(jìn)行隱式轉(zhuǎn)換
A c; //調(diào)用默認(rèn)構(gòu)造函數(shù)
c = 2; //成功,存在匹配的拷貝賦值函數(shù)
c.print();
return 0;
}</pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容