簡體   English   中英

從沒有默認構造函數的類繼承的類

[英]Class inherited from class without default constructor

現在我有一個繼承自B類的A類,而B沒有默認構造函數。 我正在嘗試為A創建一個構造函數,該構造函數與B的構造函數具有完全相同的參數

struct B {
  int n;
  B(int i) : n(i) {}
};

struct A : B {
  A(int i) {
    // ...
  }
}; 

但我得到:

error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)

我將如何修復此錯誤?

構造函數應如下所示:

A(int i) : B(i) {}

冒號后面的位表示“使用其int構造函數初始化此對象的 B 基類子對象,值為 i”。

我猜您沒有為 B 提供初始化程序,因此默認情況下編譯器會嘗試使用不存在的 no-args 構造函數初始化它。

您需要通過類的初始值設定項列表調用基本構造函數。

例子:

class C : public B
{
public:
    C(int x) : B(x)
    {
    }

};

當您不顯式初始化 B 時,它將嘗試使用沒有參數的默認構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM