explicit关键字
【1】explicit什么意思?什么作用?
explicit 翻译(划重点):
显式作用,代码举例说明如下:
(1)加关键字explicit。无法实现隐式转换。
示例代码如下:
1 #include <iostream> 2 using namespace std; 3 4 class Test 5 { 6 public: 7 explicit Test(int x = 0); // 关键字explicit的标准位置 8 void operator=(const Test &Test); 9 ~Test(); 10 void print(); 11 12 private: 13 int value; 14 }; 15 16 Test::Test(int x) :value(x) //实现时不用再添加 17 { 18 cout << "Constructor Function:" << this << endl; 19 } 20 21 void Test::operator=(const Test & t) 22 { 23 value = t.value; 24 cout << "=" << endl; 25 } 26 27 Test::~Test() 28 { 29 cout << "Destructor Function:" << this << endl; 30 } 31 32 void Test::print() 33 { 34 cout << value << endl; 35 } 36 37 void main() 38 { 39 Test T1(10); 40 // Test T2 = 10; // 编译错误 41 } 42 43 // The result of this 44 /* 45 Constructor Function:0022F750 46 Destructor Function:0022F750 47 */
(2)不加关键字explicit。可以多角度的转换,实现隐式转换,构建新对象。
示例代码如下:
1 #include<iostream> 2 using namespace std; 3 4 class Test 5 { 6 private: 7 int value; 8 9 public: 10 Test(int x = 0) :value(x) 11 { 12 cout << "Constructor Function:" << this << endl; 13 } 14 void operator=(const Test & t) 15 { 16 value = t.value; 17 cout << "=" << endl; 18 } 19 ~Test() 20 { 21 cout << "Destructor Function:" << this << endl; 22 } 23 void print() 24 { 25 cout << value << endl; 26 } 27 }; 28 29 void main() 30 { 31 Test t1(10);//直接构建对象t1 32 t1.print(); 33 cout << endl; 34 //等价于Test(66) 35 //直接创建对象t2 36 Test t2 = 66; 37 t2.print(); 38 cout << endl; 39 //隐式类型转换 40 //1>创建t3 41 //2>调用构造函数创建临时对象 42 //3>赋值函数 43 //注意:如果将构造函数定义为explicit,则编译有误!!!! 44 int a = 20; 45 Test t3; 46 t3 = a; 47 t3.print(); 48 cout << endl; 49 //强制类型转换 50 int b = 99; 51 Test t4; 52 t4 = (Test)b; 53 t4.print(); 54 } 55 56 //The result of this 57 /* 58 Constructor Function:0x0012FF70 59 10 60 61 Constructor Function:0x0012FF6C 62 66 63 64 Constructor Function:0x0012FF64 65 Constructor Function:0x0012FF58 66 = 67 Destructor Function:0x0012FF58 68 20 69 70 Constructor Function:0x0012FF5C 71 Constructor Function:0x0012FF54 72 = 73 Destructor Function:0x0012FF54 74 99 75 Destructor Function:0x0012FF5C 76 Destructor Function:0x0012FF64 77 Destructor Function:0x0012FF6C 78 Destructor Function:0x0012FF70 79 */
【2】总结
关键字explicit:专针对构造函数,抑制隐式转换。
Good Good Study, Day Day Up.
顺序 选择 循环 总结