'明确'g ++中的关键字对简单构造函数(不是复制/赋值构造函数)无效吗?
任何人都可以解释为什么以下代码会编译吗?我希望它会得到一个错误,其中 double
常量 3.3
不能转换为 int
,因为我将构造函数声明为明确的
.
Can anyone explain why the following code compiles? I expect it to get an error where the double
constant 3.3
can not be converted to int
, since I declare the constructor to be explicit
.
class A
{
public:
int n;
explicit A(int _n);
};
A::A(int _n)
{
n = _n;
}
int main()
{
A a(3.3); // <== I expect this line to get an error.
return 0;
}
显式class_name(params)(1)
显式运算符类型()(自C ++ 11起)(2)
explicit class_name ( params ) (1)
explicit operator type ( ) (since C++11) (2)
1)指定仅考虑将此构造函数用于直接初始化(包括显式转换)
1) specifies that this constructor is only considered for direct initialization (including explicit conversions)
2)指定仅将用户定义的转换函数用于直接初始化(包括显式转换)
2) specifies that this user-defined conversion function is only considered for direct initialization (including explicit conversions)
在您的情况下,您是使用直接初始化通过执行以下操作来构造类型为 A
的实例:
In your case you are using direct initialization to construct an instance of type A
by doing this:
A a(3.3);
显式关键字不会阻止编译器隐式地从int的双精度型.它阻止您执行以下操作:
The explicit keyword does not stop the compiler from implicitly casting your argument from a double type to an int. It stops you from doing something like this:
A a = 33;