C++子类析构问题

下面是我写的一个测试代码
**************base.h*****************
创建基类class base
#ifndef __base_h
#define __base_h
class 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

 

总结:当子类的对象直接释放时:

            先调用子类自身的析构函数 再调用基类的析构函数

        当子类的对象被强制转换为基类类型时:

            直接调用基类的析构函数,忽略掉子类的析构函数

 

 


 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值