前天网易C++的笔试题中的一道
输出为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;
- }
参见C++ Primer(Edition 4th) page:497.
结合上一篇虚析构函数,如果把test类析构函数设为非virtual的,则输出为ABA。