![](/img/trans.png)
[英]Can a static method in a derived class call a protected constructor in C++?
[英]C++ How can I call superclass constructor with two parameters from derived class constructor with one parameter?
例如,這:
class shape {
private:
int height;
int width;
public:
shape(int h, int w) {
height = h;
width = w;
}
void display() {
std::cout << height << "\t" << width << std::endl;
}
};
class square : public shape {
public:
square(int d) {
shape(d, d);
}
};
我收到以下錯誤消息:
no default constructor exists for class "shape"
為什么會這樣呢? 我知道它想要基類的默認構造函數,我想知道為什么要這樣做,如果我將square
構造函數的語法更改為初始化列表, square(int d): shape(d, d){}
。 程序成功編譯。 有什么區別?
只需通過這樣調用構造函數即可:
class square : public shape {
public:
square(int d): shape(d, d)
{
}
};
重要的是在派生類的構造函數的主體之前調用構造函數。 您還應該在構造函數主體之前初始化成員變量。
如果您不這樣做,則將完成所有對象的默認初始化,然后將分配作為第二步。 在您的示例中,您首先嘗試使用父類的默認初始化,這是不可能的,因為您沒有默認構造函數。
有關此主題的更多信息,請參見: http : //en.cppreference.com/w/cpp/language/initializer_list
有什么區別?
對於第一個示例,將首先默認初始化基類子對象(然后導致錯誤)。 shape(d, d);
在構造函數的主體內部只是創建一個臨時shape
,它與當前對象無關。
對於第二個對象,即square(int d): shape(d, d){}
,使用成員初始化器列表 ,基類子對象由構造函數shape::shape(int h, int w)
初始化。
在構成構造函數功能體的復合語句開始執行之前,所有直接基數,虛擬基數和非靜態數據成員的初始化已完成。 成員初始化程序列表是可以指定這些對象的非默認初始化的位置。 對於無法默認初始化的成員(例如引用成員和const限定類型的成員),必須指定成員初始化程序。
當定義了parameterized constructor
函數shape(int h, int w) { }
並且no default constructor
明確定義no default constructor
編譯器將不會調用default constructor
這就是為什么它會顯示錯誤。
因此,要么添加default constructor
要么按照您的建議添加
square(int d): shape(d, d){
/* ... */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.