【问题标题】:Why does defining a copy constructor for derived class requires that the default constructor for base class be defined?为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
【发布时间】:2020-04-23 19:24:24
【问题描述】:

我在单个 cpp 文件中有以下代码:

class Base
{
  public:
    //constructor
    Base() = delete;
};

class Derived : public Base
{
  public:
    //copy constructor
    Derived( const Derived & other ){};
};

int main( int argc, char* argv[] )
{
  //empty
}

但是编译cpp文件会出错

exp.cpp:在复制构造函数“Derived::Derived(const Derived&)”中:
exp.cpp:15:37:错误:使用已删除的函数“Base::Base()”
Derived(const Derived & other){};

exp.cpp:7:5: 注意:这里声明
Base() = 删除;
^~~~

我不明白为什么。为派生类定义复制构造函数时,基类默认构造函数如何发挥作用?

【问题讨论】:

  • 如果你写得正确,它不会。基类也需要一个拷贝构造函数,你需要调用它派生拷贝构造函数。

标签: c++ constructor copy-constructor derived-class


【解决方案1】:

构造派生类的对象需要构造其基类的对象(因为派生实例是基类实例+扩展)。

因此初始化派生实例需要初始化基实例。那么问题是当我为派生类调用一个ctor时,基类的哪个ctor被调用了?正如您将派生的ctor定义为:

Derived( const Derived & other ){};

编译器观察到您没有指定对特定基类 ctor 的调用,然后它会生成一个不带参数的 ctor 调用。但是,唉,你把它从基类中删除了。然后它会发出一个错误。

您可能认为调用派生类的复制 ctor 会生成对未删除的基类的复制 ctor 的调用。但是,唉,不,规则是,如果您没有为基类指定特定的 ctor 调用,则会调用不带参数的 ctor。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 2011-02-24
    • 2012-02-28
    • 1970-01-01
    • 2013-01-28
    • 2014-06-23
    • 2018-02-24
    • 2016-07-19
    相关资源
    最近更新 更多