Parametized Constructor Not an Copy one

房东的猫 提交于 2019-12-11 13:54:57

问题


Say we have a class A that contains as a member of the same class:

Class A{
   const A &a;
}

I want to create a parametized constructor that passed the value of that member, but I do not want to define the copy constructor of the class.

A(const A& memberA): a(memberA)     {}

How could indicate the compiler such thing?

Thanks


回答1:


A constructor that can take just a reference to the class it constructs is a copy constructor, whether you want it to be one or not. Copy constructors are defined thus:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.

You could declare it explicit to restrict how the class can be copied (preventing A a = A() for example), but it's still a copy constructor as long as it has that signature.




回答2:


You can define this constructor as explicit.

(That's a good rule for all constructors that can be called with one parameter.)



来源:https://stackoverflow.com/questions/13413419/parametized-constructor-not-an-copy-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!