本文介紹了來自構造函數的 C++ 虛函數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
為什么下面的示例打印0",并且必須改變什么才能像我預期的那樣打印1"?
#include <iostream>
struct base {
virtual const int value() const {
return 0;
}
base() {
std::cout << value() << std::endl;
}
virtual ~base() {}
};
struct derived : public base {
virtual const int value() const {
return 1;
}
};
int main(void) {
derived example;
}
推薦答案
因為 base
是先構造的,還沒有成熟"成 derived
.當它不能保證對象已經正確初始化時,它不能調用對象的方法.
Because base
is constructed first and hasn't "matured" into a derived
yet. It can't call methods on an object when it can't guarantee that the object is already properly initialized.
這篇關于來自構造函數的 C++ 虛函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!