当我删除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.
更多推荐
发布评论