Where do quot;pure virtual function callquot; crashes come from?(“纯虚函数调用在哪里?崩溃从何而来?)
问题描述
我有时会注意到程序在我的计算机上崩溃并显示错误:纯虚函数调用".
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
}
这篇关于“纯虚函数调用"在哪里?崩溃从何而来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“纯虚函数调用"在哪里?崩溃从何而来?
基础教程推荐
- C语言3个整数的数组 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C语言数组 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- C++多态 1970-01-01
- 总计将在节日礼物上花多少钱 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- 对 STL 容器的安全并行只读访问 2022-10-25
