为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
Why does defining a copy constructor for derived class requires that the default constructor for base class be defined?
我在单个 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。
相关文章:
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 当类成员参数具有相同的名称时,如何定义构造函数?
- C++定义构造函数使对象成为非 POD
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 不为 emplace() 定义构造函数的解决方法
- 已定义构造函数的构造函数无法识别
- 在自定义构造函数中的堆上创建指针
- c++ 17 中结构自动定义构造函数的规则是什么?
- Python 错误:在 SWIG 生成的C++模板化代码模块中没有定义构造函数
- unique_ptr看不到派生类的自定义构造函数
- 两种类型的定义构造函数有什么区别?第一个使用":",第二个用大括号(如函数)定义它
- 为什么一个非平凡的成员需要为同一类中的匿名联合定义构造函数
- 为其成员根据模板基类存在的类定义构造函数
- 如何在派生类上具有默认行为,而不是重新定义构造函数
- 在结构中定义构造函数
- 将从基类继承的构造函数与自定义构造函数混合使用
- 如何在模板类外部定义构造函数
- C 需要使用自定义构造函数的帮助
- 可以联合包含具有用户定义构造函数的类的对象
- 具有用户定义构造函数的非聚合类的值初始化