我正在阅读有关虚拟析构函数和虚拟函数的注释。现在,当我尝试编写一个简单的代码来验证我的学习时,
#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
我很困惑。
我g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
在 Ubuntu 12.04 中使用。