When constructor is explicit, it isn't used for implicit conversions. In the given snippet, constructor is marked as explicit
. Then why in case foo obj1(10.25);
it is working and in foo obj2=10.25;
it isn't working ?
#include <iostream>
class foo
{
int x;
public:
explicit foo( int x ):x(x)
{}
};
int main()
{
foo obj(10.25); // Not an error. Why ?
foo obj2 = 10.25; // Error
getchar();
return 0;
}
error: error C2440: 'initializing' : cannot convert from 'double' to 'foo'
These two forms of initialization are technically different. The first (foo obj(10.25);
) is called direct initialization. The second (foo obj = 10.25;
) is called copy initialization.
explicit
constructors can only be used when you explicitly initialize an object. Direct initialization is one form of explicitly initializing an object. The other form of explicit initialization is the use of a cast.
There is a difference between these two lines of code. The first line,
foo obj(10.25);
explicitly calls your foo
constructor passing in 10.25
. This syntax, in general, is a constructor call.
The second line,
foo obj2 = 10.25;
tries to implicitly convert from 10.25
to an object of type foo
, which would require use of an implicit conversion constructor. In this example, you've marked the constructor explicit
, there's no implicit conversion constructor available, and so the compiler generates an error.
Your "not an error" case is an explicit construction. The compiler is doing what you told it to do.
In the first case you are not implicitly converting 10.25
to foo
. You are converting it to an int
, so it's not an error. Saying foo obj(10.25)
is regarded as a direct call to the constructor to initialize a foo
object.
In the second case, you are trying to implicitly convert 10.25
to a foo
. The constructor marked explicit
will not be considered (as you rightfully say), and therefor you will get an error.
精彩评论