explicit的主要用法就是放在单参数的构造函数中,
防止隐式转换, 导致函数的入口参数, 出现歧义.
如果可以使用A构造B,未加explicit的构造函数, 当使用B进行参数处理时, 就可以使用A, 使得接口混乱.
为了避免这种情况, 使用explicit避免隐式构造, 只能通过显示(explicit)构造.
下面是代码, 仔细阅读必有收获, 可以试着删除explicit, 调用注释的语句.
/*************************************************
File: main.cpp
Copyright: C.L.Wang
Author: C.L.Wang
Date: 2014-04-01
Description: explicit
Email: morndragon@126.com
**************************************************/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
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;
}
输出:
B's constructor
function
转自:
http://blog.csdn.net/caroline_wendy/article/details/22727823