【1】explicit如何使用?以及作用?
举例说明如下:
(1)加关键字explicit。无法实现隐式转换。
示例代码如下:
1 #include2 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 this44 /*45 Constructor Function:0022F75046 Destructor Function:0022F75047 */
(2)不加关键字explicit。可以多角度的转换,实现隐式转换,构建新对象。
示例代码如下:
1 #include2 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);//直接构建对象t132 t1.print();33 cout << endl;34 //等价于Test(66) 35 //直接创建对象t236 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 this57 /*58 Constructor Function:0x0012FF7059 1060 61 Constructor Function:0x0012FF6C62 6663 64 Constructor Function:0x0012FF6465 Constructor Function:0x0012FF5866 =67 Destructor Function:0x0012FF5868 2069 70 Constructor Function:0x0012FF5C71 Constructor Function:0x0012FF5472 =73 Destructor Function:0x0012FF5474 9975 Destructor Function:0x0012FF5C76 Destructor Function:0x0012FF6477 Destructor Function:0x0012FF6C78 Destructor Function:0x0012FF7079 */
【2】总结
关键字explicit:专针对构造函数,抑制隐式转换。
Good Good Study, Day Day Up.
顺序 选择 循环 总结