使用带有g ++的虚拟关键字的奇怪(?)行为(Ubuntu)

时间:2013-07-24 03:18:08

标签: c++ g++

我正在阅读有关虚拟析构函数和虚函数的说明。现在,当我尝试编写一个简单的代码来验证我的学习时,

#include <iostream>
using namespace std;

class Base{
    public:
    Base (){
        cout << "Constructing base" <<endl;
    }
    void doSomething (){
        cout << "inside void " << endl;
    }
    ~Base (){
        cout << "Destructing base" << endl;
    }
};
class Derived : public Base{
    public:
    Derived(){
        cout << "Constructing derived" << endl;
    }
    void doSomething (){
        cout << "inside derived void " << endl;
    }
    ~Derived(){
        cout << "Destructing derived" << endl;
    }
};
int main(){
    Derived *d = new Derived();
    d->doSomething();
    delete d;
}

我不应该期望这样的输出:

Constructing base
Constructing derived
inside void
Destructing base

因为我没有将virtual关键字用于派生和基础的析构函数?您能否根据此示例解释虚函数和虚拟析构函数?

我得到了这个输出:

Constructing base
Constructing derived
inside derived void 
Destructing derived
Destructing base

我很困惑。

我在Ubuntu 12.04中使用g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

1 个答案:

答案 0 :(得分:1)

您获得了正确的输出。

Derived *d = new Derived();
d->doSomething();

它正在调用Derived类成员函数。要使运行时函数调用分派机制起作用,您需要使用virtual关键字限定成员函数。你也应该写 -

Base *d = new Derived();

在上述情况下,d的静态类型与动态类型不同。因此,派生类成员函数将在运行时调用。此外,在这种情况下,Base类析构函数应为virtual