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

0 0