C++子類析構問題

來源:互聯網
上載者:User
下面是我寫的一個測試代碼
**************base.h*****************
建立基類class base
#ifndef __base_h#define __base_hclass base{public:base(int a,int b);~base();public:int m;int n;};#endif
**************base.cpp***************
#include "stdafx.h"#include "base.h"base::base(int a, int b){m=a;n=b;printf("gou zao ji lei\n");}base::~base(){printf("xi gou ji lei\n");}

 

**************frombase.h************

建立子類frombase繼承基類class base

#ifndef __use_h#define __use_h#include "base.h"class frombase:public base{public: frombase(int q,int w,int e,int r); ~frombase();public: int x; int y;};#endif

************frombase.cpp************

#include "stdafx.h"#include "use.h"frombase::frombase(int q,int w,int e,int r):base(e,r){x=q;y=w;}frombase::~frombase(){printf("xi gou frombase\n");}

C++ 控制台程式測試 11

#include "stdafx.h"#include "base.h"#include "use.h"//int _tmain(int argc, _TCHAR* argv[])int main(){ int aa =1; int bb =2; int cc = 3; int dd = 4; base* _base; frombase * _frombase; _base = (base*)new frombase(aa,bb,cc,dd); printf("%d %d\n",_base->m,_base->n); delete _base; getchar(); return 0;}執行結果::

構造基類base

構造子類frombase

3 4

析構基類 base

 C++ 控制台程式測試 22

#include "stdafx.h"#include "base.h"#include "use.h"int main(){int aa =1;int bb =2;int cc = 3;int dd = 4;base* _base;frombase * _frombase;_base = (base*)new frombase(aa,bb,cc,dd);printf("%d %d\n",_base->m,_base->n);_frombase  = (frombase*)_base;printf("%d %d %d %d\n",_frombase->m,_frombase->n,_frombase->x,_frombase->y);delete _frombase;getchar();return 0;}執行結果:::

構造基類 base

構造子類 frombase

3 4

3 4 1 2

析構子類 frombase
析構基類 base

 

總結:當子類的對象直接釋放時:

            先調用子類自身的解構函式 再調用基類的解構函式

        當子類的對象被強制轉換為基類類型時:

            直接調用基類的解構函式,忽略掉子類的解構函式

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.