正常析构及析构在多继承基类中产生的不足
#include <iostream>
using namespace std;
//////////////////////////////////////////////////////////////////////////
// 正常析构解决不了父类new子类时析构函数调用的问题
// 也就是构造函数被调用了四次,而析构函数却被调用了三次
//
// 正常析构不能解决父子类同台出现的某些极端情况
/*
class A
class B
class A
class B
first delete A
class ~A
second delete B
class ~B
class ~A
*/
class A
{
public:
A()
{
cout << "class A" << endl;
}
~A()
{
cout << "class ~A" << endl;
}
};
class B: public A
{
public:
B()
{
cout << "class B" << endl;
}
~B()
{
cout << "class ~B" << endl;
}
};
int main1()
{
A* a = new B();
B* b = new B();
cout << "first delete A" << endl;
delete a;
cout << "second delete B" << endl;
delete b;
return 0;
}
虚析构能解决上述所产生的问题
#include <iostream>
using namespace std;
//////////////////////////////////////////////////////////////////////////
// 用虚基类析构函数能解决正常析构函数不能解放完的问题
/*
class AA
class BB
class AA
class BB
fir delete delete
class ~BB
class ~AA
sec delete delete
class ~BB
class ~AA
*/
class AA
{
public:
AA()
{
cout << "class AA" << endl;
}
virtual ~AA()
{
cout << "class ~AA" << endl;
}
};
class BB :public AA
{
public:
BB()
{
cout << "class BB" << endl;
}
~BB()
{
cout << "class ~BB" << endl;
}
};
int main()
{
AA* a = new BB();
BB* b = new BB();
cout << "fir delete delete" << endl;
delete a;
cout << "sec delete delete" << endl;
delete b;
return 0;
}
时间: 2025-01-08 21:57:02