[英]Why I am not getting error in following code?
#include <iostream>
using namespace std;
class A
{
private:
float data_member;
public:
A(int a);
explicit A(float d);
};
A::A(int a)
{
data_member = a;
}
A::A(float d)
{
data_member = d;
}
void Test(A a)
{
cout<<"Do nothing"<<endl;
}
int main()
{
Test(12);
Test(12.6); //Expecting a compile time error here
return 0;
}
I am expecting a error int this case as my CTOR that takes float value is explicit. 我期望在这种情况下出现错误,因为我的采用浮点值的CTOR是显式的。 But I am not getting any error in VS 2010. Please point me out if I am wrong with my understanding of keyword "EXPLICIT" in c++.
但是我在VS 2010中没有出现任何错误。如果我对c ++中的关键字“ EXPLICIT”的理解不正确,请指出。
explicit A(float d);
Does not do you think it does. 您认为没有。 It disables the implicit conversion from
float
to the type A
. 它禁用从
float
到类型A
的隐式转换。 In short, It disables any implicit conversion wherein a float will be implicitly converted to a object of A
. 简而言之,它禁用任何隐式转换,其中浮点数将隐式转换为
A
的对象。 For ex: 例如:
void doSomething(A obj){}
doSomething(2.3);
It does not disable any implicit conversions allowed by the standard. 它不会禁用标准允许的任何隐式转换。
Why does it compile?
为什么编译?
Test(12.6);
Because the float
parameter is implicitly converted to int
. 因为
float
参数隐式转换为int
。 What happens behind the scenes is same as: 幕后发生的事情与以下内容相同:
float a = 12.6;
int b = (int)a;
Further, the conversion constructor A::A(int a)
is used to create a object of type A
which is passed to the method Test()
. 此外,转换构造函数
A::A(int a)
用于创建类型A
的对象,该对象传递给方法Test()
。
Why does it not compile if you remove the
explicit
?如果删除
explicit
为什么不编译?
Without the keyword explicit
the conversion constructor A::A(float d)
is available for conversions and this creates a ambiguity because there are two possible matches, when converting 12.6
to object of type A
: 如果没有
explicit
关键字,则转换构造函数A::A(float d)
可用于转换,这会产生歧义,因为将12.6
转换为A
类型A
对象时,存在两个可能的匹配项:
A::A(int a)
or 要么
A::A(float d)
Since none scores over other in terms of best match, the compiler emits the diagnostic of ambiguity. 由于没有一个在最佳匹配方面得分超过其他,因此编译器发出了歧义的诊断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.