C++中使用構(gòu)造函數(shù)進(jìn)行類型轉(zhuǎn)換
可給類提供重載的構(gòu)造函數(shù),即接受一個或多個參數(shù)的構(gòu)造函數(shù)。這種構(gòu)造函數(shù)常用于進(jìn)行類型轉(zhuǎn)換。請看下面的 Human 類,它包含一個將整數(shù)作為參數(shù)的重構(gòu)構(gòu)造函數(shù):
class Human
{
int age;
public:
Human(int humansAge): age(humansAge) {}
};
// Function that takes a Human as a parameter
void DoSomething(Human person)
{
cout << "Human sent did something" << endl;
return;
}
這個構(gòu)造函數(shù)讓您能夠執(zhí)行下面的轉(zhuǎn)換:
Human kid(10); // convert integer in to a Human
DoSomething(kid);
這樣的轉(zhuǎn)換構(gòu)造函數(shù)讓您能夠執(zhí)行隱式轉(zhuǎn)換:
Human anotherKid = 11; // int converted to Human
DoSomething(10); // 10 converted to Human!
函數(shù) DoSothing(Human person)被聲明為接受一個 Human(而不是 int)參數(shù)!前面的代碼為何可行呢?這是因為編譯器知道 Human 類包含一個將整數(shù)作為參數(shù)的構(gòu)造函數(shù), 進(jìn)而替您執(zhí)行了隱式轉(zhuǎn)換:將您提供的整數(shù)作為參數(shù)發(fā)送給這個構(gòu)造函數(shù),從而創(chuàng)建一個 Human 對象。
為避免隱式轉(zhuǎn)換,可在聲明構(gòu)造函數(shù)時使用關(guān)鍵字 explicit:
class Human
{
int age;
public:
explicit Human(int humansAge): age(humansAge) {}
};
并非必須使用關(guān)鍵字 explicit,但在很多情況下,這都是一種良好的編程實踐。以下示例程序演示了另一個版本的 Human 類,這個版本不允許隱式轉(zhuǎn)換:
#include<iostream>
using namespace std;
class Human
{
int age;
public:
// explicit constructor blocks implicit conversions
explicit Human(int humansAge) : age(humansAge) {}
};
void DoSomething(Human person)
{
cout << "Human sent did something" << endl;
return;
}
int main()
{
Human kid(10); // explicit converion is OK
Human anotherKid = Human(11); // explicit, OK
DoSomething(kid); // OK
// Human anotherKid = 11; // failure: implicit conversion not OK
// DoSomething(10); // implicit conversion
return 0;
}
輸出:
Human sent did something
分析:
無輸出的代碼行與提供輸出的代碼行一樣重要。這個 Human 類包含一個使用關(guān)鍵字 explicit 聲明的構(gòu)造函數(shù),如第 8 行所示,而第 17~27 行的 main()以各種不同的方式實例化這個類。使用 int 來實例化 Human 類的代碼行執(zhí)行的是顯式轉(zhuǎn)換,都能通過編譯。第 23 和 24 行涉及隱式轉(zhuǎn)換,它們被注釋掉了,但如果將第 8 行的關(guān)鍵字 explicit 刪掉,這些代碼行也能通過編譯。這個實例表明,使用關(guān)鍵字
explicit 可禁止隱式轉(zhuǎn)換。
提示:
運算符也存在隱式轉(zhuǎn)換的問題,也可在運算符中使用關(guān)鍵字 explicit 來禁止隱式轉(zhuǎn)換。
該文章會更新,歡迎大家批評指正。文章來源:http://www.zghlxwxcb.cn/news/detail-758286.html
推薦一個零聲學(xué)院的C++服務(wù)器開發(fā)課程,個人覺得老師講得不錯,
分享給大家:Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒體,CDN,P2P,K8S,Docker,
TCP/IP,協(xié)程,DPDK等技術(shù)內(nèi)容
點擊立即學(xué)習(xí):C/C++后臺高級服務(wù)器課程文章來源地址http://www.zghlxwxcb.cn/news/detail-758286.html
到了這里,關(guān)于C++中使用構(gòu)造函數(shù)進(jìn)行類型轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!