为什么为派生类定义复制构造函数需要定义基类的默认构造函数?

Why does defining a copy constructor for derived class requires that the default constructor for base class be defined?

本文关键字:定义 构造函数 基类 默认 复制 为什么 派生      更新时间:2023-10-16

我在单个 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::D erived(const Derived&(':


exp.cpp:15:37: 错误: 使用已删除的函数 'Base::Base(('
Derived( const Derived & other ({};

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

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

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

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

Derived( const Derived & other ){};

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

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