#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();
}
虚析构和纯虚析构
最新推荐文章于 2024-05-13 14:11:50 发布