自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C++虛析構(gòu)函數(shù)基本內(nèi)容概述

開發(fā) 后端
我們在這里將會通過一段代碼示例的解讀來為大家詳細分析一下C++虛析構(gòu)函數(shù)的相關(guān)應用方法以及基本概念,讓大家對此有一個充分的掌握。

 

今天,我們將會在這篇文章中為大家詳細介紹一下C++虛析構(gòu)函數(shù)的一些基本知識。相信對于剛剛接觸C++編程語言的初學者們現(xiàn)在急需要諸如這方面的基礎知識的講解內(nèi)容,以加大自己對這一語言的認知。#t#

C++的多態(tài)性是通過虛函數(shù)來實現(xiàn)的,虛函數(shù)的出現(xiàn)使得動態(tài)鏈接成為可能。

基于構(gòu)造函數(shù)的特點,不能將構(gòu)造函數(shù)定義為虛函數(shù),但可以將析構(gòu)函數(shù)定義為虛函數(shù)。當派生類的對象從內(nèi)存中撤銷時,會先調(diào)用派生類的析構(gòu)函數(shù),然后自動調(diào)用基類的析構(gòu)函數(shù),如此看來析構(gòu)函數(shù)也沒有必要定義為虛函數(shù)。

但是考慮如下這種情況,如果使用基類指針指向派生類的對象,而這個派生類對象恰好是用new運算創(chuàng)建的,這種情況下會如何呢?當程序使用delete運算撤銷派生類對象時,這時只會調(diào)用基類的析構(gòu)函數(shù),而沒有調(diào)用派生類的析構(gòu)函數(shù)。如果使用的是虛析構(gòu)函數(shù)的話,就不一樣了,所以定義虛析構(gòu)函數(shù)有時候還是很有必要的。下面這段程序就說明了上面的問題:

沒有定義虛C++虛析構(gòu)函數(shù)時,code如下:

 

  1. #include < iostream> 
  2. using namespace std;  
  3. class A  
  4. {  
  5. public:  
  6. A(){}  
  7. ~A()  
  8. {  
  9. cout< < "A::destructor"< < endl;  
  10. }  
  11. };  
  12. class B:public A   
  13. {  
  14. public:  
  15. B(){}  
  16. ~B()  
  17. {  
  18. cout< < "B::destructor"< < endl;  
  19. }  
  20. };  
  21. int main()  
  22. {  
  23. A *pA = new B;  
  24. //  
  25. delete pA;  
  26. return 0;  

輸出的是A::destructor

這說明delete pA只是調(diào)用了基類A的析構(gòu)函數(shù),而沒有調(diào)用子類B的析構(gòu)函數(shù),這不是我們所想要的。而把基類A的析構(gòu)函數(shù)定義為虛函數(shù)后,就可以達到了我們所想要的效果了。code如下:

  1. #include < iostream> 
  2. using namespace std;  
  3. class A  
  4. {  
  5. public:  
  6. A(){}  
  7. virtual ~A()  
  8. {  
  9. cout< < "A::destructor"< < endl;  
  10. }  
  11. };  
  12. class B:public A   
  13. {  
  14. public:  
  15. B(){}  
  16. ~B()  
  17. {  
  18. cout< < "B::destructor"< < endl;  
  19. }  
  20. };  
  21. int main()  
  22. {  
  23. A *pA = new B;  
  24. //  
  25. delete pA;  
  26. return 0;  

輸出如下:

B::destrutor

A::destrutor

以上就是對C++虛析構(gòu)函數(shù)的相關(guān)介紹。

責任編輯:曹凱 來源: 博客園
相關(guān)推薦

2010-02-06 13:58:13

C++ Bost庫

2010-02-02 15:12:09

C++ explici

2024-12-19 14:42:15

C++內(nèi)存泄漏內(nèi)存管理

2010-02-05 10:08:55

C++名字空間

2010-02-04 15:51:07

C++迭代器

2025-02-18 00:08:00

代碼C++RAII

2010-01-28 15:33:37

Android程序架構(gòu)

2010-03-02 15:53:02

WCF服務合同

2010-01-18 15:53:27

C++析構(gòu)函數(shù)

2010-02-04 16:39:26

C++析構(gòu)函數(shù)

2010-02-03 15:06:02

C++可變參數(shù)表

2010-03-02 17:55:37

WCF終結(jié)點地址

2025-04-11 07:50:00

虛析構(gòu)函數(shù)C++開發(fā)

2011-07-15 01:29:39

C++析構(gòu)函數(shù)

2010-02-25 17:04:54

WCF實例上下文

2009-08-14 17:24:28

C#構(gòu)造函數(shù)和析構(gòu)函數(shù)

2009-09-03 13:14:55

C#構(gòu)造函數(shù)C#析構(gòu)函數(shù)

2010-01-04 15:21:37

Silverlight

2010-02-01 11:22:09

C++虛函數(shù)

2022-07-18 15:32:37

C++虛函數(shù)表
點贊
收藏

51CTO技術(shù)棧公眾號