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.
g()函数中,调用f(I)出错的原因:“没有一个可用的隐式转换可从int到X类型。”
Note It is meaningless to apply explicit to constructors with multiple arguments, since such constructors cannot take part in implicit conversions.
注释:多参数的构造器直接应用explicit关键字是无意义的,应用了explicit后,构造器不能进行部分的隐式转换.
END 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.