C++ 如何在派生类中声明复制构造函数,而基类中没有默认构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9309577/
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 12:38:44  来源:igfitidea点击:

How to declare copy constructor in derived class, without default construcor in base?

c++inheritancecopy-constructor

提问by unresolved_external

Please take a look on the following example:

请看下面的例子:

class Base
{
protected:
    int m_nValue;

public:
    Base(int nValue)
        : m_nValue(nValue)
    {
    }

    const char* GetName() { return "Base"; }
    int GetValue() { return m_nValue; }
};

class Derived: public Base
{
public:
    Derived(int nValue)
        : Base(nValue)
    {
    }
    Derived( const Base &d ){
        std::cout << "copy constructor\n";
    }

    const char* GetName() { return "Derived"; }
    int GetValueDoubled() { return m_nValue * 2; }
};

This code keeps throwing me an error that there are no default contructor for base class. When I declare it everything is ok. But when i dont, code does not work.

这段代码不断向我抛出一个错误,即基类没有默认构造函数。当我宣布它时一切正常。但是当我不这样做时,代码不起作用。

How can I declare a copy constructor in derived class without declaring default contructor in base class?

如何在派生类中声明复制构造函数而不在基类中声明默认构造函数?

Thnaks.

纳克斯。

回答by Nawaz

Call the copy-constructor (which is generated by the compiler) of the base:

调用基类的复制构造函数(由编译器生成):

Derived( const Derived &d ) : Base(d)
{            //^^^^^^^ change this to Derived. Your code is using Base
    std::cout << "copy constructor\n";
}

And ideally, you should call the compiler generated copy-constructor of the base. Don't think of calling the other constructor. I think that would be a bad idea.

理想情况下,您应该调用编译器生成的基类复制构造函数。不要想着调用另一个构造函数。我认为那将是一个坏主意。

回答by PlasmaHH

You can (and should) call the copy ctor of the base class, like:

您可以(并且应该)调用基类的复制构造函数,例如:

Derived( const Derived &d ) :
        Base(d)
{
    std::cout << "copy constructor\n";
}

Note that I turned the Base parameter into a Derived parameter, since only that is called a copy ctor. But maybe you didn't really wanted a copy ctor...

请注意,我将 Base 参数转换为 Derived 参数,因为只有它才称为复制构造函数。但也许你并不真正想要一个复制 ctor...