如何解决“调用纯虚方法"?

How to resolve quot;pure virtual method calledquot;(如何解决“调用纯虚方法?)

本文介绍了如何解决“调用纯虚方法"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白为什么会发生这种情况,但我一直在尝试解决它...这是我的代码在我的程序退出时生成错误(因此导致崩溃)时所做的事情...

I understand why this is happening, but I'm stuck trying to resolve it...here is what my code is doing when the error is generated (thus, leading to a crash) when my program exits...

调用的纯虚方法

SomeClass::~SomeClass()
{
   BaseClassObject->SomePureVirtualMethod(this);
}

<小时>

void DerivedClass::SomePureVirtualMethod(SomeClass* obj)
{
    //Do stuff to remove obj from a collection
}

我从来没有调用过 new SomeClass 但我有一个 QList<SomeClass*> 我将 SomeClass* 对象附加到它.SomeClass 中的这个析构函数的目的是告诉 DerivedClassQListSomeClass 的特定实例>.

I never have a call to new SomeClass but I have a QList<SomeClass*> which I append SomeClass* objects to. The purpose of this destructor in SomeClass is to tell DerivedClass to remove a specific instance of SomeClass from it's collection of QList<SomeClass*>.

所以,举个具体的例子……

So, in a concrete example...

BaseClass = 形状

DerivedClass = 三角形

SomeClass = ShapeProperties 拥有对 Shape

所以,我从来没有调用过 new ShapeProperties,但我在 Triangle 中有一个 QList.ShapeProperties 中的析构函数是告诉 TriangleQList 的集合中删除 ShapeProperties 的特定属性/代码>.

So, I never have a call to new ShapeProperties but I have a QList<ShapeProperties*> inside of Triangle. The destructor in ShapeProperties is to tell Triangle to remove a specific property of ShapeProperties from it's collection of QList<ShapeProperties*>.

推荐答案

当你的析构函数被调用时,继承类的析构函数已经被调用了.在构造函数和析构函数中,可以有效地将对象的动态类型视为与静态类型相同.也就是说,当您从构造函数/析构函数中调用虚方法时,调用的不是它们的覆盖版本.

By the time your destructor is called, the destructor of inherited classes has already been called. Within constructors and destructors, the dynamic type of the object can effectively be considered to be the same as the static type. That is, when you call virtual methods from within your constructors/destructors it's not the overriden versions of them that are called.

如果 SomePureVirtualMethod 需要在析构函数中调用,那么你必须在你想要的方法的实际定义所在的类的析构函数中调用它.

If SomePureVirtualMethod needs to be called at the destructor, then you will have to call it within the destructor of the class where the actual definition of the method you want is.

这篇关于如何解决“调用纯虚方法"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何解决“调用纯虚方法"?

基础教程推荐