虚析构:
#include<iostream>
#include<string>
using namespace std;
class Animal {
public:
//纯虚函数
virtual void speak() = 0;
Animal()
{
cout << "Anima构造函数调用" << endl;
}
~Animal()
{
cout << "Anima析构函数调用" << endl;
}
};
class Cat :public Animal {
public:
Cat(){}
Cat(string name)
{
cout << "调用了空参构造" << endl;
m_Name = new string(name);
}
//重写
virtual void speak()
{
cout <<*m_Name<< "小猫在喵喵" << endl;
}
~Cat() {
if (m_Name != NULL)
{
cout << "Cat析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void test01()
{
Animal * animal = new Cat("TOM");
animal->speak();
delete animal;
}
int main() {
test01();
}
此时,Cat析构函数未执行,堆区有内存未释放,将父类析构函数设为虚析构函数
父类指针在析构时候 不会调用子类中析构函数,导致子类如果有堆区属性,出现内存泄漏
可以利用虚析构解决,父类指针释放子女对象时不干净的问题
#include<iostream>
#include<string>
using namespace std;
class Animal {
public:
//纯虚函数
virtual void speak() = 0;
Animal()
{
cout << "Anima构造函数调用" << endl;
}
//利用虚析构可以解决,父类指针释放子类对象时不干净的问题
//析构函数加上virtual关键字,变成虚析构函数
virtual ~Animal()
{
cout << "Anima虚析构函数调用" << endl;
}
};
//和包含普通纯虚函数的类一样,包含了纯虚析构函数的类,也是一个抽象类,不能够被实例化
class Cat :public Animal {
public:
Cat(){}//空参构造
Cat(string name)//有参构造
{
cout << "Cat调用了构造函数" << endl;
m_Name = new string(name);
}
//重写
virtual void speak()
{
cout <<*m_Name<< "小猫在喵喵" << endl;
}
~Cat() {
if (m_Name != NULL)
{
cout << "Cat析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void test01()
{
Animal * animal = new Cat("TOM");
animal->speak();
delete animal;
}
int main() {
test01();
}
纯虚析构:
需要声明,需要具体实现,否则报错,有了纯虚析构之后,这个类也属于抽象类,无法实例化对象
#include<iostream>
#include<string>
using namespace std;
class Animal {
public:
//纯虚函数
virtual void speak() = 0;
Animal()
{
cout << "Anima构造函数调用" << endl;
}
//纯虚析构
virtual ~Animal() = 0;
};
class Cat :public Animal {
public:
Cat(){}
Cat(string name)
{
cout << "Cat调用了构造函数" << endl;
m_Name = new string(name);
}
//重写
virtual void speak()
{
cout <<*m_Name<< "小猫在喵喵" << endl;
}
~Cat() {
if (m_Name != NULL)
{
cout << "Cat析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void test01()
{
Animal * animal = new Cat("TOM");
animal->speak();
//父类指针在析构时候 不会调用子类中析构函数,导致子类如果有堆区属性,出现内存泄漏
delete animal;
}
int main() {
test01();
}
#include<iostream>
#include<string>
using namespace std;
class Animal {
public:
//纯虚函数
virtual void speak() = 0;
Animal()
{
cout << "Anima构造函数调用" << endl;
}
//纯虚析构声明
virtual ~Animal() = 0;
};
//纯虚析构具体实现
Animal::~Animal()
{
cout << "Anima纯虚析构函数调用" << endl;
}
class Cat :public Animal {
public:
Cat(){}
Cat(string name)
{
cout << "Cat调用了构造函数" << endl;
m_Name = new string(name);
}
//重写
virtual void speak()
{
cout <<*m_Name<< "小猫在喵喵" << endl;
}
~Cat() {
if (m_Name != NULL)
{
cout << "Cat析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void test01()
{
Animal * animal = new Cat("TOM");
animal->speak();
//父类指针在析构时候 不会调用子类中析构函数,导致子类如果有堆区属性,出现内存泄漏
delete animal;
}
int main() {
test01();
}