C++中的explicit
生活随笔
收集整理的這篇文章主要介紹了
C++中的explicit
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
explicit
- 前言
- 0x00 explicit
前言
C++中, 一個類的構造函數(或者除了第一個參數外其余參數都有默認值的多參構造函數), 承擔了兩個角色。
1.是個構造器
2.是個默認且隱含的類型轉換操作符。
0x00 explicit
C++中的關鍵字 explicit 主要是用來修飾類的構造函數,被修飾的構造函數的類,不能發生相應的隱式類型轉換,只能以顯示的方式進行類型轉換。類構造函數默認情況下聲明為隱式的即 implicit 。
explicit關鍵字作用于單個參數的構造函數,如果構造函數有多個參數,但是從第二個參數開始,如果各參數均有默認賦值,也可以應用explicit關鍵字防止隱式轉換。
class VectorInt2D { public:VectorInt2D(){Init();}explicit VectorInt2D(int x) // explicit防止隱式轉換{Init(x);}VectorInt2D(int x, int y){Init(x, y);}VectorInt2D(const VectorInt2D& obj){this->x = obj.x;this->y = obj.y;// 重新申請新的內存空間uint32_t nLen = strlen(obj.m_pszClassName) + 1;m_pszClassName = new char[nLen];strcpy_s(m_pszClassName, nLen, obj.m_pszClassName);}void Init(int x = 0, int y = 0){uint32_t nLen = strlen("VectorInt2D") + 1;m_pszClassName = new char[nLen];strcpy_s(m_pszClassName, nLen, "VectorInt2D");this->x = x;this->y = y;}~VectorInt2D(){if (m_pszClassName != nullptr){delete m_pszClassName;m_pszClassName = nullptr;}}char* GetClassName(){return m_pszClassName;}int GetX(){return this->x;}int GetY(){return this->y;} private:char* m_pszClassName;int x;int y; };void ShowPoint(VectorInt2D pos) {printf("%s x=%d y=%d\n", pos.GetClassName(), pos.GetX(), pos.GetY()); }int main(int argc, char* argv[]) {VectorInt2D pos1(1, 2);// 參數為對象自動匹配構造函數 這里匹配拷貝構造ShowPoint(pos1);// 顯式調用構造函數VectorInt2D pos2(2);//編譯錯誤,不能隱式調用其構造函數ShowPoint(1); // error C2664: “void ShowPoint(VectorInt2D)”: 無法將參數 1 從“int”轉換為“VectorInt2D”return 0; }如果構造函數explicit VectorInt2D(int x)中去掉 explicit 關鍵字,則ShowPoint(1);可以調用成功。這時會發生隱式轉換,用 1 構造 VectorInt2D 對象,然后傳參給 ShowPoint 函數。
總結
以上是生活随笔為你收集整理的C++中的explicit的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sun x4600
- 下一篇: 2019丘成桐中学科学奖计算机,2019