explicit
C++ Specific
This keyword is a declaration specifier that can only be applied to in-class constructor declarations. Constructors declared explicit will not be considered for implicit conversions. For example:
class X {
public:
explicit X(int); //legal
explicit X(double) { //legal
// ...
}
};
explicit X::X(int) {} //illegal
An explicit constructor cannot take part in implicit conversions. It can only be used to explicitly construct an object. For example, with the class declared above:
void f(X) {}
void g(int I) {
f(i); // will cause error
}
void h() {
X x1(1); // legal
}
The function call f(i) fails because there is no available implicit conversion from int to X.
Note It is meaningless to apply explicit to constructors with multiple arguments, since such constructors cannot take part in implicit conversions.
END C++ Specific
http://hi.baidu.com/qiangsoft/blog/item/ef67a6835bd35eb56d811934.html
explicit
C++中, 一个参数的构造函数, 承担了两个角色。 1 是个构造器 2 是个默认且隐含的类型转换操作符。
所以, 有时候在我们写下如 AAA = XXX, 这样的代码, 且恰好XXX的类型正好是AAA单参数构造器的参数类型, 这时候编译器就自动调用这个构造器, 创建一个AAA的对象。
这样看起来好象很酷, 很方便。 但在某些情况下(见下面权威的例子), 却违背了我们(程序员)的本意。 真是成也萧何, 败也萧何。 这时候就要在这个构造器前面加上explicit修饰, 指定这个构造器只能被明确的调用,使用, 不能作为类型转换操作符被隐含的使用。 呵呵, 看来还是光明正大些比较好。
explicit构造函数的作用
解析:
explicit构造函数是用来防止隐式转换的。请看下面的代码:
1 class Test1
2 {
3 public:
4 Test1(int n) { num = n; } //普通构造函数
5 private:
6 int num;
7 };
8
9 class Test2
10 {
11 public:
12 explicit Test2(int n) { num = n; } //explicit(显式)构造函数
13 private:
14 int num;
15 };
16
17 int main()
18 {
19 Test1 t1 = 12; //隐式调用其构造函数, 成功
20 Test2 t2 = 12; //编译错误,不能隐式调用其构造函数
21 Test2 t3(12); //显示调用成功
22 return 0;
23 }
Test1的构造函数带一个int型的参数,代码19行会隐式转换成调用Test1的这个构造函数。而Test2的构造函数被声明为explicit(显式),这表示不能通过隐式转换来调用这个构造函数,因此代码20行会出现编译错误。
普通构造函数能够被隐式调用。而explicit构造函数只能被显示调用。