how does this Implicit conversion happen?
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
class B has a constru开发者_运维技巧ctor B(A a) takes object a as a object,but inside the constructor of B, it does nothing. so how does this happens?
The constructor of B
which takes a parameter of type A
gets called when you write B b=a
. Its true that constructor of B
does nothing with the argument a
, but that is a different thing altogether.
Its equivalent to:
B b(a); //equivalent to "B b = a;"
The syntax B b=a
invokes the constructor of B
which takes A
as argument; after that what the constructor does with the argument a
, has nothing to do with the constructor's invocation!
It is like the following case, when you write f(100)
, you're passing 100 to f()
; now it f
does nothing with the 100
, its a different story. It doesn't has anything to do with the function invocation.
void f(int a)
{
return;
}
f(100);
so how does this happens?
B(A a) gets called. Pretty much the same thing that would happen in that constructor as if b was default constructed with an empty default constructor. Default constructors on members of B are executed.
This is happening because in C++, while calling constructor, implicit conversion for one parameter is allowed.
For eg. if you have the following class:
class A
{
int a;
public:
A(int _a):a(_a){}
} ;
Then, the following statement is valid:
A ob = 5 ;
equivalent to `A ob(int(5)) ;`
Drawing analogy from this example, in your case, B b = a;
can be expanded as B b(A(a));
Further, you can read about explicit keyword in C++
Note: The example above is just for reference so please ignore the equivalent notations for syntactical validation
Conversion from A to B means, "construct an instance of B, passing an instance of A as a constructor parameter".
Whether B actually uses that instance of A to do anything in the constructor is irrelevant. It's still a conversion, whether or not the value of the A instance has any effect on the result.
B
's constructor doesn't need to do anything.
By creating the [non-explicit] constructor that takes an A
as a parameter, you're making A
convertible to B
.
The constructor body is where you can specify behaviours that should be performed upon such a construction, but since you didn't write anything there (and nothing in the ctor-initializer
, either), nothing happens.
The actual construction of the B
still occurs, as usual, thanks to the language.
You just get the B
, as if you'd created it through any other constructor you could come up with, either without arguments or with arguments that you never get around to using.
BTW, you should probably accept A& const
, not A
.
精彩评论