explicit关键字用于取消构造函数的隐式转换,对有多个参数的构造函数使用explicit是个语法错误。
In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion. For example:
class A {
public:
A(int);
};
void f(A) {}
void g()
{
A a1 = 37;
A a2 = A(47);
A a3(57);
a1 = 67;
f(77);
}
A declaration like:
A a1 = 37;
says to call the A(int) constructor to create an A object from
the integer value. Such a constructor is called a "converting
constructor".
However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = 37; // illegal
A a2 = A(47); // OK
A a3(57); // OK
a1 = 67; // illegal
f(77); // illegal
}
Using the explicit keyword, a constructor is declared to be
"nonconverting", and explicit constructor syntax is required:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = A(37);
A a2 = A(47);
A a3(57);
a1 = A(67);
f(A(77));
}
Note that an expression such as:
A(47)
is closely related to function-style casts supported by C++. For example:
double d = 12.34;
int i = int(d);
explicit,和构造函数一起使用.
explicit constructor指明构造函数只能显示使用,目的是为了防止不必要的隐式转化.
举个例子:
有这样一段代码:
class A
{
public:
A(int);
private:
int num;
};
int Test(const A&) // 一个应用函数
{
...
}
Test(2); // 正确
过程是这样的: 编译器知道传的值是int而函数需要的是A类型,但它也同时知道调用A的构造函数将int转换成一个合适的A,所以才有上面成功的调用.换句话说,编译器处理这个调用时的情形类似下面这样:
const A temp(2); // 从2产生一个临时A对象
Test(temp); // 调用函数
如果代码写成如下样子:
class A
{
public:
explicit A(int);
private:
int num;
};
int Test(const A&) // 一个应用函数
{
...
}
Test(2); // 失败,不能通过隐式类型转换将int类型变量构造成成A类型变量
禁止單參數的構造函數隐式转化為參數類型!
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.
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
explicit: 禁止隐式类型转换操作
explicit 它与 virtual、inline 合称为“函数限定符”。它只适用于构造函数。若一个类拥有只带一个参数的构造函数,则可以使用 MyClass object(x) 或 MyClass
object = x
来初始化对象,这实际是进行了从参数类型到类类型的转换。若在在构造函数前加上限定符
explicit ,将不再允许这种转换,即不允许 MyClass object = x 这种形式。