如何在派生类中声明复制构造函数,而不在基础中使用默认的construcor? [英] How to declare copy constructor in derived class, without default construcor in base?

查看:145
本文介绍了如何在派生类中声明复制构造函数,而不在基础中使用默认的construcor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下示例:

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。

推荐答案

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

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.

这篇关于如何在派生类中声明复制构造函数,而不在基础中使用默认的construcor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆