在C ++中从父析构函数调用子方法 [英] Calling child method from parent destructor in C++

查看:74
本文介绍了在C ++中从父析构函数调用子方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {
public:
  ~A() { release(); }
  virtual release() { cout << "~A"; } 
}

class B : public A {
  release() { cout << "~B"; }
}

删除B时,仅调用A类release()方法.

When I delete B, only A class release() method is called.

我想要实现的是为每个子对象删除对象后,我要调用在每个子类中被覆盖的释放方法,而无需为每个子对象手动指定析构函数来调用释放(我很懒).用这种或其他方式实际上是不可能实现的吗?

What I want to achieve is for every child object, when it is deleted, I want to call release method which is overriden in each child class, without manually specifying destructor for each child with call to release (I'm lazy). Is this actually not possible to achieve in this or any other way?

推荐答案

析构函数是按构造函数的相反顺序执行的,因此,当 A B 中的code>被破坏了,它的 B 组件已经被破坏了,不再存在.在被破坏的对象上调用方法会产生未定义的行为,这就是为什么对虚拟方法的调用总是解析为构造函数中的当前类类型的原因,或者析构函数.

Destructors are executed in the reverse order of constructors, so when the A in a B is destroyed its B component has already been destroyed and no longer exists. Calling a method on a destroyed object yields undefined behavior, and that's why calls to virtual methods always resolve to the current class type within a constructor or destructor.

所以基本上不,您不能这样做.您将不得不全部编写.

So basically no, you cannot do it. You will have to write them all.

这篇关于在C ++中从父析构函数调用子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆