博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
explicit关键字
阅读量:4313 次
发布时间:2019-06-06

本文共 2494 字,大约阅读时间需要 8 分钟。

【1】explicit如何使用?以及作用?

举例说明如下:

(1)加关键字explicit。无法实现隐式转换。

 示例代码如下:

1 #include 
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 this44 /*45 Constructor Function:0022F75046 Destructor Function:0022F75047 */

 (2)不加关键字explicit。可以多角度的转换,实现隐式转换,构建新对象。

 示例代码如下:

1 #include
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);//直接构建对象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.

顺序 选择 循环 总结

转载于:https://www.cnblogs.com/Braveliu/archive/2012/12/30/2840055.html

你可能感兴趣的文章
应用程序缓存的应用(摘抄)
查看>>
C#析构函数,类运行结束后运行
查看>>
在LAMP的生产环境内添加PHP的cURL扩展模块
查看>>
AMH 软件目录介绍
查看>>
你可能使用了Spring最不推荐的注解方式
查看>>
java常见3种文件上传速度对比和文件上传方法详细代码
查看>>
SVD总结
查看>>
python基础教程(三)
查看>>
PL SQL Developer中文乱码
查看>>
字符串知识大全
查看>>
软件目录结构规范及堂兄弟文件引用
查看>>
H5 WebSocket通信和WCF支持WebSocket通信
查看>>
文件上传
查看>>
不能在此路径中使用此配置节。如果在父级别上锁定了该节,便会出现这种情况...
查看>>
Linux的IO性能监控工具iostat详解
查看>>
老杨聊架构:每个架构师都应该研究下康威定律
查看>>
1022: 锤子剪刀布
查看>>
RESTful-rest_framework认证组件、权限组件、频率组件-第五篇
查看>>
手机自带功能调用
查看>>
百度搜索引擎取真实地址-python代码
查看>>