C++工作笔记-虚函数、纯虚函数、虚析构函数的进一步理解
生活随笔
收集整理的這篇文章主要介紹了
C++工作笔记-虚函数、纯虚函数、虚析构函数的进一步理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
虛函數:
1.帶virtual關鍵字;
2.父類有定義,并且有功能,子類繼承后可以重寫這個功能(在Qt中經常見到?父類::此函數(參數)進行父類的調用,這樣做是為了把父類的邏輯"繼承"下來);
?
純虛函數:
1.帶virtual關鍵字;
2.函數尾巴后面帶=0;
3.在C++中一般充當接口的功能;
?
虛析構函數:
1.帶virtual關鍵字;
2.目的是為了把內存釋放干凈(造成這樣的原因是因為父類指向子類對象,delete父類后,子類不會析構(除非父類是虛析構函數,不然不會被釋放))
?
下面來一個栗子:
代碼如下:
#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(); }?
程序運行截圖如下:
一共有4個部分:
這里就說明下最后2個部分,
倒數第二個部分:
Base里面有個虛析構函數,所有雖然他被delete掉了,但他會先去調用子類的虛構函數。
倒數第一個部分:
API這個類里面的析構函數不是虛析構函數,所以他沒有調用子類的析構函數,這樣就造成內存釋放不干凈!
總結
以上是生活随笔為你收集整理的C++工作笔记-虚函数、纯虚函数、虚析构函数的进一步理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ opengl 使视野转头移动(
- 下一篇: s3c2440移植MQTT