下面是我寫的一個測試代碼
**************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
總結:當子類的對象直接釋放時:
先調用子類自身的解構函式 再調用基類的解構函式
當子類的對象被強制轉換為基類類型時:
直接調用基類的解構函式,忽略掉子類的解構函式