【发布时间】:2011-01-30 10:26:48
【问题描述】:
让我声明一下:我对构造函数或析构函数中的虚函数调用有清晰的了解。
在下面的代码中,我试图避免虚拟析构函数仅用于实验目的。
现在我的问题是:
在 main 中,对 Destroy fun 的调用调用了正确的虚函数。 我希望对 Destroy Function 的任何调用都应该调用正确的虚拟乐趣。
但是放置在 Base 析构函数调用中的同一个 Destroy 函数是 Base 虚函数。
这与静态绑定或编译器优化有关吗?
class Base
{
public:
Base()
{
}
void Destroy()
{
callVirtual();
}
virtual void callVirtual()
{
cout<<"In Base callVirtual "<<endl;
}
~ Base()
{
cout<<"In Base Destructor"<<endl;
Destroy();
}
};
.
class Derived : public Base
{
public:
Derived()
{
}
void callVirtual()
{
cout"<<In Derived callVirtual"<<endl;
}
};
.
int main()
{
Base *pointer = new Derived();
pointer->Destroy(); // Calls the right callVirtual
return 0;
}
【问题讨论】:
-
我不明白您的示例代码与您的问题有什么关系。请你澄清一下析构函数与任何东西有什么关系?
-
@Oil Charlesworh:主要是调用 Destroy fun 调用正确的虚函数。我希望对 Destroy Function 的任何调用都应该调用正确的虚拟乐趣。这与析构函数中的静态绑定有关吗???????但是放置在 Base 析构函数调用的 Base 虚函数中的同一个 Destroy 函数
-
你对在构造函数/析构函数中调用虚函数有一个清晰的认识,你会问这样的问题。 wtf?
-
@VJo: 可能现在我对 cotr/Dstr 中的 virtual 有了清晰的认识
-
"我对构造函数或析构函数中的虚函数调用有清楚的了解。"不,你没有。
标签: c++ object-lifetime virtual-destructor overriding