C++ 继承复制构造函数调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12640468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:28:02  来源:igfitidea点击:

C++ inherited copy constructor call ?

c++constructorcopycopy-constructor

提问by kiriloff

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 ? Or how to do this ? Is this the good way:

当我为 B 类调用复制构造函数时,这个复制构造函数会自动调用吗?或者如何做到这一点?这是好方法吗:

A::A(A* a)
{
    B(a);
    // copy stuff
}

thanks!

谢谢!

回答by Jon

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.

不要忘记,如果您自己实现复制构造函数,则应遵循三规则

回答by Luchian Grigore

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() { }

i.e. your copy constructor from class A won't be automatically called. You need:

即不会自动调用类 A 中的复制构造函数。你需要:

B(const B& other) : A(other) { }