C++ 虛建構函式
只有當基類指標指向派生類物件時,虛機制才會起作用。
在 C++ 中,建構函式不能是虛的,因為當執行類的建構函式時,記憶體中沒有虛表,這意味著尚未定義虛指標。因此,建構函式始終應為非虛的。
但可能的虛解構函式。
示例程式碼
#include<iostream>
using namespace std;
class b {
public:
b() {
cout<<"Constructing base \n";
}
virtual ~b() {
cout<<"Destructing base \n";
}
};
class d: public b {
public:
d() {
cout<<"Constructing derived \n";
}
~d() {
cout<<"Destructing derived \n";
}
};
int main(void) {
d *derived = new d();
b *bptr = derived;
delete bptr;
return 0;
}輸出
Constructing base Constructing derived Destructing derived Destructing base
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP