问题
When I declare my copy constructor as explicit, calling it using = instead of () doesn't compile. Here's my code:
class Base
{
public:
explicit Base(){cout<<__PRETTY_FUNCTION__<<endl;}
explicit Base(Base& b){cout <<__PRETTY_FUNCTION__<<endl;}
};
int main()
{
Base a;
Base b=a;
}
The compiler says:
error: no matching function for call to ‘Base::Base(Base&)’
If I change it to
Base b(a);
It compiles fine. I thought C++ considers these two styles of instantiations the same. If I remove the explicit keyword it does works both ways. I'm guessing there is some implicit conversion going on when I use =. So what am I missing here?
回答1:
No, they are not the same. C++ Standard section § 12.3.1 [class.conv.ctor]
An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used
Base b(a); // Direct initialization
Base b=a; // Copy initialization
Copy initialization (using =
) doesn't consider explicit constructors, but direct initialization (using ()
) does.
You'll have to use a cast or make your constructor non explicit if you want to use copy initialization.
来源:https://stackoverflow.com/questions/28010392/explicit-copy-constructor-call-syntax