關鍵字explicit,用於構造函數,可以阻止構造函數的隱式轉換,構造函數聲明explicit後如果使用隱式轉換會報錯。
隱式轉換:例
class Person
{
public:
Person(int age);
......
}
......
Person Tom = 20;//調用隱式轉換,等同於
//Person temp(20);
//Person Tom = temp;
有的時候不需要隱式轉換,或者隱式轉換會帶來一些意想不到的問題:
class Person
{
public:
Person(int age);
Person(const char* name);
......
}
......
Person tom = 20;//tom的年齡爲20
Person tom = "tom";//tom的名字爲tom
Person lucy = 'a';//lucy的年齡爲int('a')=97
這三條語句都編譯通過了,但是lucy的年齡爲97歲並不是我們想要的
如果在兩個構造函數的前面都加上explicit修飾後,再執行上述代碼就會出現編譯錯誤,cannot convery form 類型 to class Person
explicit Person(int age);
explicit Person(const char* name);