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

编程入门 行业动态 更新时间:2024-10-28 09:19:44
在C ++中从父析构函数调用子方法(Calling child method from parent destructor in C++) class A { public: ~A() { release(); } virtual release() { cout << "~A"; } } class B : public A { release() { cout << "~B"; } }

当我删除B时,只调用一个class release()方法。

我想要实现的是每个子对象,当它被删除时,我想调用在每个子类中重写的释放方法,而不需要为每个调用release的子项手动指定析构函数(我是懒惰的)。 这实际上是不可能以这种方式或任何其他方式实现的?

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

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?

最满意答案

析构 函数构造函数的相反顺序执行,因此当B中的B被销毁时,其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.

更多推荐

本文发布于:2023-08-02 23:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382530.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   方法   Calling   父析构   parent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!