c++继承实例

请参照原文:http://blog.csdn.net/zhaori/article/details/1700356

 

//Example:  non- virtual destructors for dynamically allocated objects.
 

#include <iostream>
#include <string.h>
using  std::endl;
using std::cout;

class Thing
{
public:
virtual void what_Am_I( ) {cout << "I am a Thing.\n";}
virtual ~Thing(){cout<<"Thing destructor"<<endl;}
};

class Animal :  Thing

public:
virtual void what_Am_I( ) {cout << "I am an Animal.\n";}
virtual ~Animal(){cout<<"Animal destructor"<<endl;}
};

void main( )
{
   Thing *t =new Thing;     
   Animal*x = new Animal;
         

    for (int i=0; i<2; i++) 
 {
     if(i==0) t->what_Am_I( ) ;


   else if(i==1)
   
           x->what_Am_I( ) ;
   
 }


 delete t;
 delete x;
    return ;
}

/*
**********小结***************************************
* 如果基类中没有虚析构函数,则删除派生类对象时
* 不会调用派生类的析构函数,此时也就会造成
* 内存泄漏。

* 另外,创建派生类对象时,会先创建一个基类对象

* 所以delete x  时,也会调用基类的析构函数。
* 解决办法: 将基类的析构函数设置成虚析构函数
*******************************************************
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值