问题:执行如下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关键字,则代码的执行结果为: