c++ explicit在构造函数中的应用
来源:互联网 发布:java 文件拷贝 编辑:程序博客网 时间:2024/06/06 04:00
explicit的主要用法就是放在单参数的构造函数中,防止隐式转换, 导致函数的入口参数, 出现歧义.
如果可以使用A构造B, 未加explicit的构造函数, 当使用B进行参数处理时, 就可以使用A, 使得接口混乱.
为了避免这种情况, 使用explicit避免隐式构造, 只能通过显示(explicit)构造.
下面是代码, 仔细阅读必有收获, 可以试着删除explicit, 调用注释的语句.
[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
/***************************************
File: main.cpp
Copyright: C.L.Wang
Author: C.L.Wang
Date: 2014-04-01
Description: explicit
Email: morndragon@126.com
****************************************/
#include
using namespace std;
class A {};
class B {
public:
// conversion from A (constructor):
explicit B (const A& x) {
std::cout << “B’s constructor” << std::endl;
}
// conversion from A (assignment):
B& operator= (const A& x) {
std::cout << “B’s assignment” << std::endl;
return *this;
}
// conversion to A (type-cast operator)
operator A() {
std::cout << “B’s conversion” << std::endl;
return A();
}
};
void fn (B arg) {
std::cout << “function” << std::endl;
}
int main ()
{
A foo;
B bar(foo);
//B bar = foo; // calls constructor, 添加explicit出错, 不能默认构造
//bar = foo; // calls assignment
//foo = bar; // calls type-cast operator
//fn(foo); //添加explicit出错, 就不能默认的隐式转换
fn(bar);
return 0;
}
参考:http://blog.csdn.net/caroline_wendy/article/details/22727823
- c++ explicit在构造函数中的应用
- explicit构造函数(C++)
- 【C++】explicit构造函数
- [C++]explicit构造函数
- C++ 中的explicit构造函数
- C++ explicit在构造函数中的作用解析
- explicit在C++中的应用
- explicit构造函数的具体应用
- C++ 中的关键字-------explicit 修饰构造函数
- QObject构造函数explicit
- explicit构造函数
- [转]explicit构造函数
- explicit构造函数
- explicit构造函数
- explicit构造函数
- explicit构造函数
- explicit构造函数
- explicit构造函数
- autocomplete根据输入字符进行搜索
- spring boot 发送邮件带附件出现Not in multipart mode - create an appropriate MimeMessageHelper错误
- 需要的图
- android studio自带调试工具
- Qt中编写槽函数 (对两种不同的触发方式 值改变和单击按钮 进行 试验)
- c++ explicit在构造函数中的应用
- java常用加密方式代码实现
- Testing 802.11n systems - Part 2: MIMO configuration analysis
- Struts2配置(Struts开发流程)
- 2016年已经悄然无声的走过,2017悄悄然来到自己的身边
- opencv 删除二值化图像中面积较小的连通域
- 设计模式的六大原则(简单的概念)
- UnityShader实例09:Stencil Buffer&Stencil Test
- vue2.0 下拉框默认标题设置