析构函数的问题---->大虾快来!!!!!(50分)

  • 主题发起人 主题发起人 sun2000
  • 开始时间 开始时间
S

sun2000

Unregistered / Unconfirmed
GUEST, unregistred user!
有如下的类定义,为什么会对Parent::~Parent()调用三次??????
class TParent
{
public:
TParent() {}
virtual __fastcall ~TParent()
{ ShowMessage("TParent Destructor");
}
};
class TChild: public TParent
{
public:
TChild(): TParent() {}
vitual __fastcall ~TChild()
{ ShowMessage("TChild Destructor");
}
};
int main(void)
{
TParent *Parent = new TParent();
TChild *Child = new TChild();
FreeObjects(Parent);
FreeObjects(Child);
}
 
由于TChild是TParent的子类,且~TParent又是在Public域中,当然要执行3次了!
 
Hi Jams
我还是不懂,你能否讲清楚点???
第一次是FreeObjects(Parent);
-->Parent::~Parent();
<1>
第二次是FreeObjects(Child);
-->Child::~Child();
第三次是 -->Parent::~Parent();
<2>
???????为什么调用了~Child后还要调用~Parent??????
 
FreeObjects是谁写的?
代码贴出来看看。
 
FreeObjects如下:
void FreeObjects(TParent* Parent)
{
delete Parent;
}
 
Hint:
your Child::~Child() implementation will
still call CParent::~CParent();
 
pegasus你来了就好了,欢迎!
是否子类的析构函数都会调用父类得析构函数??????
 
Yeah, 请看下面这段文字,是C++的关于析构函数的说明
Order of Destruction
When an object goes out of scope or is deleted, the sequence of events in its complete destruction is as follows:
The class’s destructor is called, and the body of the destructor function is executed.
Destructors for nonstatic member objects are called in the reverse order in which they appear in the class declaration. The optional member initialization list used in construction of these membersdo
es not affect the order of construction or destruction.
Destructors for nonvirtual base classes are called in the reverse order of declaration.
Destructors for virtual base classes are called in the reverse order of declaration
 
pegasus 谢谢!!
听说你是南京的,有机会能见见吗?
 
后退
顶部