原文:https://www.jianshu.com/p/f05073044daf
詳細參考:https://blog.csdn.net/l2563898960/article/details/97769569
1.explicit函數介紹
- 作用:explicit構造函數是用來防止隱式轉換的
- 實例1如下
#include <iostream> using namespace std; // explicit函數的介紹!!! // explicit函數的作用:explicit構造函數是用來防止隱式轉換的 class Test1{ public: Test1(int n){ // 普通隱式的構造函數 num = n; } private: int num; }; class Test2{ public: explicit Test2(int n){ //explicit(顯式)構造函數 num = n; } private: int num; }; int main(){ Test1 t1 = 12; // 隱式調用其構造函數,成功 // Test2 t2 = 12; 編譯錯誤,不能隱式調用其構造函數 Test2 t3(12); // 顯式調用成功 return 0; }
-
- Test1的構造函數帶一個int型的參數,會隱式轉換成調用Test1的這個構造函數。而Test2的構造函數被聲明為explicit(顯式),這表示不能通過隱式轉換來調用這個構造函數,因此Test2 t2 = 12會出現編譯錯誤。普通構造函數能夠被隱式調用,而explicit構造函數只能被顯式調用。
- 實例2如下
class Test{ public: Test():a(0){ cout << "void\n"; } explicit Test(int i):a(i){ cout << "int\n"; } Test(short s):a(s){ cout << "short\n"; } Test & operator=(int n){ a = n; cout << "operator = "; } private: int a; }; int main(){ int n; Test a = n; return 0; }
A:接受一個參數的構造函數允許使用賦值語句隱式調用來初始化對象; 而explicit構造函數只能被顯式調用!所以,輸出的是short!