C++關鍵字explicit

weixin_34262482發表於2012-01-05

     explicit的中文解譯是:詳盡的;清楚的;明確的。那麼explicit在C++中是什麼意思呢?

Explicit(顯示的)

(1)explicit可以禁止“單引數建構函式”被用於自動型別轉換,有效的防止了建構函式的隱式轉換帶來的錯誤。

(2)explicit只對建構函式起作用,用來抑制隱式轉換。

(3)所有的單引數的建構函式都必須是explicit的,以避免後臺的型別轉換。

用例項說明上面兩點:

#include <iostream>
using namespace std;

class People
{
public:
People(int age){}
People(string name){this->name=name;}
int age;
string name;
};

int main()
{
People people1(25);
People people2=25;

return 0;
}

上面的People people2=25編譯竟然能夠通過,將25賦給人,有點說不過去。為了避免這種情況發生就需要在建構函式上加關鍵字explicit了,程式如下:

 

#include <iostream>
using namespace std;

class People
{
public:
explicit People(int age){}
People(string name){this->name=name;}
int age;
string name;
};

int main()
{
People people1(25);
//People people2=25; //error C2440: 'initializing' : cannot convert from 'const int' to 'class People'

return 0;
}

加上關鍵字explicit後,People people2=25就編譯通不過了。

相關文章