![](/img/trans.png)
[英]Why does the implicit copy constructor calls the base class copy constructor and the defined copy constructor doesn't?
[英]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::Derived(const Derived&)”中:
exp.cpp:15:37: 錯誤:使用已刪除的函數 'Base::Base()'
派生(常量派生和其他){};
exp.cpp:7:5: 注意:此處聲明
基地()=刪除;
^~~~
我不明白為什么。 當您為派生類定義復制構造函數時,基類默認構造函數如何發揮作用?
構造派生類的對象需要構造其基類的對象(因為派生實例是基實例+擴展)。
因此初始化派生實例需要初始化基實例。 那么問題來了,當我為派生類調用 ctor 時,會調用基類的哪個 ctor? 正如您將派生 ctor 定義為:
Derived( const Derived & other ){};
編譯器觀察到您沒有指定對特定基類 ctor 的調用,然后它生成對不帶參數的 ctor 的調用。 但是,唉,你從基類中刪除了它。 然后它發出一個錯誤。
您可能認為為派生類調用復制構造函數會生成對未刪除的基類的復制構造函數的調用。 但是,唉,不,規則是,如果您沒有為基類指定特定的 ctor 調用,則調用沒有參數的 ctor。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.