随便写写看,关于析构和构造函数里面不能调用虚函数

初见这个内容是在Effective C++上,在构造函数和析构函数中调用虚函数是非常不好的行为

 

一个简单的例子

 

  1. class Base
  2. {
  3. public:
  4.     Base()
  5.     {
  6.         cout<<"Base::Base()"<<endl;
  7.     }
  8.     
  9.     ~Base()
  10.     {
  11.         fun();
  12.         cout<<"Base::~Base()"<<endl;
  13.     }
  14.     
  15.     virtual void fun()
  16.     {
  17.         cout<<"Base::fun()"<<endl;
  18.     }
  19. };
  20. class Derived : public Base
  21. {
  22. public:
  23.     Derived()
  24.     {
  25.         cout<<"D::D()"<<endl;
  26.     }
  27.     
  28.     ~Derived()
  29.     {
  30.         cout<<"D::~D()"<<endl;
  31.     }
  32.     
  33.     virtual void fun()
  34.     {
  35.         cout<<"D::fun()"<<endl;
  36.     }
  37. };
  38. void area()
  39. {
  40.     Derived d;
  41. }

 

执行 area() 后,得到的结果是

Base::Base()
D::D()
D::~D()
Base::fun()
Base::~Base()

本来在Base的析构函数中调用一个虚函数的意图很有可能是调用子类override版本

但是,由于C++的析构机制,子类总是先父类析构

所以,这样的意图不可能实现,也就是书中所说的,在析构和构造函数中的虚函数不是虚函数!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个面向对象的编程问题,下面是实现: ```c++ #include<iostream> using namespace std; class Point{ public: Point(double x = 0, double y = 0): m_x(x), m_y(y){} //构造函数 virtual ~Point(){} //函数 double getX() const {return m_x;} double getY() const {return m_y;} protected: double m_x; double m_y; }; class Rectangle: public Point{ public: Rectangle(double x = 0, double y = 0, double w = 0, double h = 0): Point(x, y), m_w(w), m_h(h){} ~Rectangle(){} double Area() const {return m_w * m_h;} protected: double m_w; double m_h; }; class Circle: public Point{ public: Circle(double x = 0, double y = 0, double r = 0): Point(x, y), m_r(r){} ~Circle(){} double Area() const {return 3.1415926 * m_r * m_r;} protected: double m_r; }; int main(){ double x, y, w, h, r; cout << "Please input the x and y coordinate of the rectangle's left-bottom point, and its width and height: "; cin >> x >> y >> w >> h; Rectangle rect(x, y, w, h); cout << "The area of the rectangle is: " << rect.Area() << endl; cout << "Please input the x and y coordinate of the circle's center and its radius: "; cin >> x >> y >> r; Circle cir(x, y, r); cout << "The area of the circle is: " << cir.Area() << endl; return 0; } ``` 输入输出示例: ``` Please input the x and y coordinate of the rectangle's left-bottom point, and its width and height: 0 0 5 6 The area of the rectangle is: 30 Please input the x and y coordinate of the circle's center and its radius: 0 0 5 The area of the circle is: 78.5398 ``` 注意,我们使用了函数,因为我们希望在使用派生类对象时,能够正确地调用函数,从而释放内存。此外,我们也使用了基类指针来访问派生类对象的成员函数,这是面向对象编程的一种常见用法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值