析构函数在调用虚函数时调用的是基类的函数
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。
#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。
相关文章推荐
- 构造函数,析构函数内调用虚函数问题
- C++基类与派生类的函数调用情况
- 不要在构造函数和析构函数中调用虚函数
- 指向子类对象的基类指针调用非虚函数都是基类的函数吗
- 如果类的析构函数在main函数返回后调用,内存泄漏检测函数应该放在这个析构函数的末尾。
- 《Effective C++ 》条款9:永远不要在构造函数或析构函数中调用虚函数
- c++调用被基类隐藏的函数
- 构造函数和析构函数能否声明为虚函数,能否在里面调用虚函数
- C++中 构造函数 析构函数 能否调用虚函数的问题
- C++中构造函数和析构函数避免调用虚函数的问题
- 派生类和基类的函数调用
- C++学习笔记(5)——基类、派生类的构造函数、析构函数的调用顺序
- 体验虚基类的析构函数和虚函数
- 构造函数为什么不能为虚函数 & 基类的析构函数为什么要为虚函数
- C++ 构造函数或析构函数调用虚函数
- 多态基类的析构函数应该为虚函数
- 多态继承情况下,有一个基类指针指向派生类对象,如何用它调用基类的虚函数?
- C++为什么基类的析构函数是虚函数
- 《Effective C++》不要在构造函数和析构函数中调用虚函数
- Python基类函数的重载与调用实例分析