多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码.
解决方法:将父类中的析构函数改为虚析构或者纯虚析构
如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
虚析构和纯虚析构共同点:
- 可以解决父类指针释放子类对象
- 都需要有具体的函数实现
虚析构和纯虚析构区别:
- 如果是纯虚析构,该类属于抽象类,无法实例化对象
虚析构语法:
virtual ~类名(){}
纯虚析构语法:
类内声明:
virtual ~类名()=0;
类外实现:
类名::~类名(){}
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
A()
{
cout << "父类构造函数调用" << endl;
}
virtual void f1() = 0;//纯虚函数
~A()
{
cout << "父类析构函数调用" << endl;
}
};
class B :public A
{
public:
B(int n1)
{
cout << "子类构造函数调用" << endl;
n = new int(n1);
}
virtual void f1()
{
cout << *n<<"B" << endl;
}
~B()
{
if (n != NULL)
{
cout << "子类析构函数调用" << endl;
delete n;
n = NULL;
}
}
int *n;
};
void t1()
{
A *a = new B(10);
a->f1();
delete a;
}
int main()
{
t1();
system("pause");
return 0;
}
子类析构函数没有调用,堆区数据没有释放干净,导致内存泄漏
利用虚析构解决:
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
A()
{
cout << "父类构造函数调用" << endl;
}
virtual void f1() = 0;//纯虚函数
virtual ~A()//改为虚析构
{
cout << "父类析构函数调用" << endl;
}
};
class B :public A
{
public:
B(int n1)
{
cout << "子类构造函数调用" << endl;
n = new int(n1);
}
virtual void f1()
{
cout << *n<<"B" << endl;
}
~B()
{
if (n != NULL)
{
cout << "子类析构函数调用" << endl;
delete n;
n = NULL;
}
}
int *n;
};
void t1()
{
A *a = new B(10);
a->f1();
//父类指针在析构时,不会调用子类的析构函数
//如果子类有堆区的属性,会出现内存泄漏
delete a;
}
int main()
{
t1();
system("pause");
return 0;
}
利用纯虚析构解决:
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
A()
{
cout << "父类构造函数调用" << endl;
}
virtual void f1() = 0;//纯虚函数
virtual ~A()=0;//纯虚析构函数
//因为父类可能也有数据开辟到堆区,所以函数内部要有实现
/*virtual ~A()
{
cout << "父类虚析构函数调用" << endl;
}*/
};
A::~A()//纯虚析构需要声明也需要实现
{
cout << "父类纯虚析构函数调用" << endl;
}
class B :public A
{
public:
B(int n1)
{
cout << "子类构造函数调用" << endl;
n = new int(n1);
}
virtual void f1()
{
cout << *n<<"B" << endl;
}
~B()
{
if (n != NULL)
{
cout << "子类析构函数调用" << endl;
delete n;
n = NULL;
}
}
int *n;
};
void t1()
{
A *a = new B(10);
a->f1();
//父类指针在析构时,不会调用子类的析构函数
//如果子类有堆区的属性,会出现内存泄漏
delete a;
}
int main()
{
t1();
system("pause");
return 0;
}
纯虚析构和虚析构只能用一个,有了纯虚析构之后,这个类也属于抽象类,无法实例化对象。