您的位置:首页 > 编程语言 > C语言/C++

一个有关C++中对象构造、析构和虚函数的问题

2012-10-15 17:10 330 查看
问题:执行如下C++代码,程序的输出是什么?

#include <iostream>
using namespace std;

class Base{
public:
Base(){
cout << "Base Constructor" << endl;
foo();
}
~Base(){
cout << "Base Destructor" << endl;
foo();
}
virtual void foo(){
cout << "Base Function" << endl;
}
};

class Derived: public Base{
public:
Derived(){
cout << "Derived Constructor" << endl;
foo();
}
~Derived(){
cout << "Derived Destructor" << endl;
foo();
}
void foo(){
cout << "Derived Function" << endl;
}
};

int main()
{
Base *p = new Derived;
delete p;
return 0;
}

分析:主函数的第一句创建了一个Derived类对象,按照C++的对象构造顺序,在构造派生类对象时,先调用基类的构造函数,再调用派生类的构造函数。基类构造函数调用了基类的foo()函数,派生类的构造函数调用了派生类的foo()函数。由于Base()类的析构函数没有定义为虚函数,主函数的第二句只调用Base类的析构函数,这样就发生了内存泄露。

以上代码的执行结果为:



如果将以上代码主函数的第一行改为Derived *p = new Derived;或者将Base类的析构函数加上virtual关键字,则代码的执行结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息