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

 前天网易C++的笔试题中的一道
  1. #include <iostream>
  2. using namespace std;

  3. class test
  4. {
  5.     int s;
  6. public:
  7.     test()
  8.     {
  9.         fun();
  10.     }
  11.     virtual ~test()
  12.     {
  13.         fun();
  14.     }
  15.     virtual void fun()
  16.     {
  17.         cout<<"A"<<endl;
  18.     }
  19. };

  20. class derived : public test
  21. {
  22.     int s;
  23. public:
  24.     derived(int i)
  25.     {
  26.         s = i;
  27.         fun();
  28.     }
  29.     ~derived()
  30.     {
  31.         fun();
  32.     }
  33.     void fun()
  34.     {
  35.         cout<<"B"<<endl;
  36.     }
  37. };

  38. int main()
  39. {
  40.     test *pr = new derived(9);
  41.     delete pr;
  42.     return 0;
  43. }
输出为ABBA。在基类构造函数或析构函数中,将派生类对象当作基类类型对象对待。如果在构造函数,析构函数中调用虚函数,则运行的是为构造函数或析构函数自身类型定义的版本。

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


结合上一篇虚析构函数,如果把test类析构函数设为非virtual的,则输出为ABA。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值