[英]C++ inherited copy constructor call ?
I have class B derived from class A. I call copy constructor that I implemented myself for an object of class B. I also implemented myself a constructor for class A. 我有从类A派生的类B.我调用了我为类B的对象实现自己的复制构造函数。我还为类A实现了自己的构造函数。
Is this copy constructor automatically called when I call copy constructor for class B ? 当我为B类调用复制构造函数时,是否会自动调用此复制构造函数? Or how to do this ?
或者怎么做? Is this the good way:
这是好方法:
A::A(A* a)
{
B(a);
// copy stuff
}
thanks! 谢谢!
You can do this with a constructor initialization list, which would look like this: 您可以使用构造函数初始化列表执行此操作,如下所示:
B::B(const B& b) : A(b)
{
// copy stuff
}
I modified the syntax quite a bit because your code was not showing a copy constructor and it did not agree with your description. 我修改了语法很多,因为您的代码没有显示复制构造函数,并且它与您的描述不一致。
Do not forget that if you implement the copy constructor yourself you should follow the rule of three . 不要忘记,如果您自己实现复制构造函数,则应遵循三条规则 。
A copy constructor has the signature: 复制构造函数具有签名:
A(const A& other) //preferred
or 要么
A(A& other)
Yours is a conversion constructor. 你的是一个转换构造函数。 That aside, you need to explicitly call the copy constructor of a base class, otherwise the default one will be called:
除此之外,您需要显式调用基类的复制构造函数,否则将调用默认值:
B(const B& other) { }
is equivalent to 相当于
B(const B& other) : A() { }
ie your copy constructor from class A won't be automatically called. 即,不会自动调用A类的复制构造函数。 You need:
你需要:
B(const B& other) : A(other) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.