#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. 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++.
explicit A(float d);
Does not do you think it does. It disables the implicit conversion from float
to the type A
. In short, It disables any implicit conversion wherein a float will be implicitly converted to a object of 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
. 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()
.
Why does it not compile if you remove the
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
:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.