4

让我声明一下:我对构造函数或析构函数中的虚函数调用有清晰的理解。

在下面的代码中,我试图避免虚拟析构函数仅用于实验目的。

现在我的问题是:

在 main 中,对 Destroy fun 的调用调用了正确的虚函数。我希望对 Destroy Function 的任何调用都应该调用正确的虚拟乐趣。

但是放置在 Base 析构函数调用的 Base 虚函数中的同一个 Destroy 函数。

这与静态绑定或编译器优化有关吗?

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;

}
4

1 回答 1

6

在析构函数中, 的动态类型this是当前类的动态类型,而不是对象的原始动态类型。参见例如http://www.artima.com/cppsource/nevercall.html

于 2011-01-30T10:45:21.600 回答