C++工作笔记-虚函数、纯虚函数、虚析构函数的进一步理解
生活随笔
收集整理的這篇文章主要介紹了
C++工作笔记-虚函数、纯虚函数、虚析构函数的进一步理解
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
虛函數(shù):
1.帶virtual關(guān)鍵字;
2.父類有定義,并且有功能,子類繼承后可以重寫這個功能(在Qt中經(jīng)常見到?父類::此函數(shù)(參數(shù))進(jìn)行父類的調(diào)用,這樣做是為了把父類的邏輯"繼承"下來);
?
純虛函數(shù):
1.帶virtual關(guān)鍵字;
2.函數(shù)尾巴后面帶=0;
3.在C++中一般充當(dāng)接口的功能;
?
虛析構(gòu)函數(shù):
1.帶virtual關(guān)鍵字;
2.目的是為了把內(nèi)存釋放干凈(造成這樣的原因是因為父類指向子類對象,delete父類后,子類不會析構(gòu)(除非父類是虛析構(gòu)函數(shù),不然不會被釋放))
?
下面來一個栗子:
代碼如下:
#include <iostream> #include <conio.h> #include <string> using namespace std;class API { public:virtual string createAWorld() = 0;virtual void alterWorldName(string name) = 0;~API() { //No virtual functioncout << "Destroy API called\n";}protected:API() {cout << "API construction called!\n";} };class Implementation :public API { public:string createAWorld() {cout << "ImplementationOne createAWorld called!\n";m_name = "earth";return "successful";}void alterWorldName(string name) {m_name = name;}~Implementation() {cout << "Destroy Implementation called\n";} private:string m_name; };class Base { public:virtual void printClassName() {cout << "The class is Base\n";}Base() {cout << "Base construction called\n";}virtual ~Base() {cout << "Virtual destroy Base Called\n";}};class Child :public Base { public:void printClassName() {cout << "The class is Child\n";cout << "farther's pinrtClassName():";Base::printClassName();}Child() {cout << "Child construction called\n";}~Child() {cout << "Destroy Child Called\n";} };void main() {Implementation *imp = new Implementation;imp->createAWorld();cout << "\n";Child *child = new Child;child->printClassName();delete child;delete imp;cout << "\n";Child *pChild = new Child;Base *base = pChild;base->printClassName();delete base;cout << "\n";API *api = new Implementation;api->createAWorld();delete api;_getch(); }?
程序運(yùn)行截圖如下:
一共有4個部分:
這里就說明下最后2個部分,
倒數(shù)第二個部分:
Base里面有個虛析構(gòu)函數(shù),所有雖然他被delete掉了,但他會先去調(diào)用子類的虛構(gòu)函數(shù)。
倒數(shù)第一個部分:
API這個類里面的析構(gòu)函數(shù)不是虛析構(gòu)函數(shù),所以他沒有調(diào)用子類的析構(gòu)函數(shù),這樣就造成內(nèi)存釋放不干凈!
總結(jié)
以上是生活随笔為你收集整理的C++工作笔记-虚函数、纯虚函数、虚析构函数的进一步理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ opengl 使视野转头移动(
- 下一篇: Qt文档阅读笔记-Qt工作笔记QProc