考虑一下:
class FluffyThing
{
public:
FluffyThing()
{
m_pMyFur = new Fur;
}
virtual ~FluffyThing();
protected:
Fur * m_pMyFur;
};
class ClawedFluffyThing : public FluffyThing
{
public:
ClawedFluffyThing()
: FluffyThing()
{
m_pMyClaws = new Claws;
}
virtual ~ClawedFluffyThing();
protected:
Claws * m_pMyClaws;
};
class ScaryFluffyThing : public ClawedFluffyThing
{
public:
ScaryFluffyThing()
: ClawedFluffyThing()
{
m_pMyTeeth = new Teeth;
m_pMyCollar = new SpikedCollar;
}
virtual ~ScaryFluffyThing();
protected:
Teeth * m_pMyTeeth;
SpikedCollar * m_pMyCollar;
};
希望没有太多错误 - 我想你明白了。要点是它们之间存在 3 个具有 IS-A 关系的类,并且每个类还具有一两个在销毁时间方面需要清理的属性。如果我没有声明虚拟析构函数,编译器会自动为我生成以下内容吗?声明了析构函数,因此被迫实现它们(假设使用了类)是遵循正确的长期方法来进行破坏吗?
FluffyThing::~FluffyThing()
{
delete m_pMyFur;
}
ClawedFluffyThing::~ClawedFluffyThing()
{
delete m_pMyClaws;
FluffyThing::~FluffyThing();
}
ScaryFluffyThing::~ScaryFluffyThing()
{
delete m_pMyTeeth;
delete m_pMyCollar;
ClawedFluffyThing::~ClawedFluffyThing();
}
肯定已经有一个明确的答案......但我无法足够快地找到我喜欢的答案。