显式复制构造函数调用语法 [英] Explicit Copy constructor call syntax
问题描述
当我将副本构造函数声明为显式时,使用=而不是()调用它不会编译.这是我的代码:
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;
}
编译器说:
错误:没有匹配的函数可以调用"Base :: Base(Base&)"
error: no matching function for call to ‘Base::Base(Base&)’
如果我将其更改为
Base b(a);
它可以编译.我以为C ++认为这两种实例化样式是相同的.如果我删除了显式关键字,它确实可以双向工作.我猜我使用=时会发生一些隐式转换.那我在这里想念什么?
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?
推荐答案
不,它们不一样.C ++标准部分第12.3.1节[class.conv.ctor]
No, they are not the same. C++ Standard section § 12.3.1 [class.conv.ctor]
一个显式构造函数像非显式一样构造对象构造函数,但仅在直接初始化语法的情况下才这样做(8.5)或明确使用强制转换(5.2.9,5.4)的地方
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.
这篇关于显式复制构造函数调用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!