使用 C++ 中的共享指標進行虛擬析構
在本教程中,我們將討論一個程式,瞭解如何使用 C++ 中的共享指標進行虛擬析構。
為了刪除類例項,我們定義虛基類的解構函式。因此,它將按建立的相反順序刪除繼承的不同物件例項。
示例
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
Base(){
cout << "Constructing Base" << endl;
}
~Base(){
cout << "Destructing Base" << endl;
}
};
class Derived : public Base {
public:
Derived(){
cout << "Constructing Derived" << endl;
}
~Derived(){
cout << "Destructing Derived" << endl;
}
};
int main(){
std::shared_ptr<Base> sp{ new Derived };
return 0;
}輸出
Constructing Base Constructing Derived Destructing Derived Destructing Base
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP