1. 程式人生 > >explicit C++關鍵字的使用 修飾的建構函式必須被顯式呼叫

explicit C++關鍵字的使用 修飾的建構函式必須被顯式呼叫

explicit 意思是明確的,清楚的。

原始碼如下:

#include <iostream>

using namespace std;


class Test1
{
public:
Test1(int n)
{
m_Name = n;
}
~Test1()
{


}


private:
int m_Name;


};




class Test2
{
public:
explicit Test2(int n)
{
m_Name = n;
}
~Test2()
{


}


int m_Name;


};




int main()
{

Test1 test1 = 1;//正確

Test1 test11= 11;  //正確

//Test2 test2 =2 ;  錯誤

Test2 test22(22);//正確

system("pause");
return 0;

}

新建一個Win32控制檯空專案,新增一個.cpp檔案,將上述程式碼拷貝其中執行即可。

總結:

Test1類可以Test1 test1 = 1;//正確,但是對於建構函式加了explicit的Test2類就不可以。

Test1的建構函式帶一個int型別的引數,Test1 test1 = 1;程式碼會隱式轉換成呼叫Test1的這個建構函式。而Test2的建構函式被宣告為explicit(顯式),這表示不能通過隱式轉換來呼叫這個建構函式,因此會出現編譯錯誤。

話外:

在C++中,一個引數的建構函式,承擔了兩個角色。1.是個構造器;2.是個預設且隱含的型別轉換操作符。