在什么地方“纯虚拟函数调用”崩溃来自? [英] Where do "pure virtual function call" crashes come from?

查看:321
本文介绍了在什么地方“纯虚拟函数调用”崩溃来自?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时会注意到程序在我的电脑上崩溃时出现错误:纯虚函数调用。

I sometimes notice programs that crash on my computer with the error: "pure virtual function call".

这些程序在无法创建对象时一个抽象类?

How do these programs even compile when an object cannot be created of an abstract class?

推荐答案

如果你尝试从构造函数或析构函数调用虚函数,因为你不能从构造函数或析构函数中调用虚函数(派生类对象没有被构造或者已经被销毁),它调用基类版本,在纯虚函数的情况下,不存在。

They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.

(请参阅实时演示此处

class Base
{
public:
    Base() { doIt(); }  // DON'T DO THIS
    virtual void doIt() = 0;
};

void Base::doIt()
{
    std::cout<<"Is it fine to call pure virtual function from constructor?";
}

class Derived : public Base
{
    void doIt() {}
};

int main(void)
{
    Derived d;  // This will cause "pure virtual function call" error
}

这篇关于在什么地方“纯虚拟函数调用”崩溃来自?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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