c++ - 如何解决 "pure virtual method called"

标签 c++ polymorphism derived-class base-class pure-virtual

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

pure virtual method called

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

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

我从来没有给 new SomeClass 打过电话但我有一个 QList<SomeClass*>我附加了SomeClass*反对。 SomeClass 中此析构函数的用途是告诉DerivedClass删除 SomeClass 的特定实例来自 QList<SomeClass*> 的集合.

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

BaseClass = Shape

DerivedClass = Triangle

SomeClass = ShapeProperties它拥有对 Shape 的引用

所以,我从来没有打过 new ShapeProperties 的电话。但我有一个 QList<ShapeProperties*> Triangle内部. ShapeProperties 中的析构函数是告诉Triangle删除 ShapeProperties 的特定属性来自 QList<ShapeProperties*> 的集合.

最佳答案

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

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

关于c++ - 如何解决 "pure virtual method called",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10707286/

相关文章:

c++ - 我可以从另一个函数中初始化静态成员吗​​?

c++ - 是否有用于存储离散间隔的集合?

C# 简化并可能概括了我的对象克隆方法

java - 如果相同的方法重载和覆盖,Java 中的意外多态行为

c# - 在构造函数中使用继承 (publix X () : y)

c++ - 如何转换简历类型 :Mat

haskell - 为什么 `[1, "a"]::[forall a. Show a => a]` 不允许?

c++ - 处理基类和派生类时如何正确编写c++ makefile

c# - 将 lambda 表达式转换为派生类型

c++ - 跟踪对 std::cout 的调用