虚析构和纯虚析构

#include<bits/stdc++.h>
using namespace std;

//虚析构和纯虚析构

class animal
{
public:
	animal()
	{
		cout<<"animal的构造"<<endl;
	} 
	//利用虚析构可以解决 父类指针释放子类对象时不干净的问题 
//	virtual ~animal()
//	{
//		cout<<"animal的析构"<<endl;
//	}

    //纯虚析构,既要声明也要实现 
    //有了纯虚析构,这个类属于抽象类,无法实例化对象 
    virtual ~animal()=0; 
	virtual void speak()=0;
}; 
animal::~animal()
{
	cout<<"animal的纯虚析构"<<endl;
}
class cat:public animal
{
public:
	cat(string name)
	{
		cout<<"cat的构造调用"<<endl;
		m_name=new string(name);
	}
	void speak()
	{
		cout<<*m_name<<"小猫在说话"<<endl; 
	}
	~cat()
	{
		if(m_name!=NULL)
		{
			cout<<"cat的析构调用"<<endl; 
			delete m_name;
			m_name=NULL;
		}
	}
	string *m_name;
};
void test()
{
	animal *t=new cat("Tom");
	t->speak();
	//父类指针在析构的时候,不会调用子类的析构函数
	//导致子类如果有堆区属性,出现内存泄露 
	delete t;
}
int main()
{
	char a[5]="hell";
	char b[6]="hello";
	
	//a大于b,返回值大于0 
	//a等于b,返回0 
	//a小于b,返回值小于0  
	cout<<strcmp(a,b)<<endl; 
	test();
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值