您的位置:首页 > 其它

析构函数在调用虚函数时调用的是基类的函数

2008-09-27 17:03 309 查看
前天网易C++的笔试题中的一道

#include <iostream>
using namespace std;

class test
{
int s;
public:
test()
{
fun();
}
virtual ~test()
{
fun();
}
virtual void fun()
{
cout<<"A"<<endl;
}
};

class derived : public test
{
int s;
public:
derived(int i)
{
s = i;
fun();
}
~derived()
{
fun();
}
void fun()
{
cout<<"B"<<endl;
}
};

int main()
{
test *pr = new derived(9);
delete pr;
return 0;
}

输出为ABBA。在基类构造函数或析构函数中,将派生类对象当作基类类型对象对待。如果在构造函数,析构函数中调用虚函数,则运行的是为构造函数或析构函数自身类型定义的版本。

参见C++ Primer(Edition 4th) page:497.

结合上一篇虚析构函数,如果把test类析构函数设为非virtual的,则输出为ABA。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: