我有时会注意到程序在我的计算机上崩溃并显示错误:“纯虚函数调用”。
当无法从抽象类创建对象时,这些程序如何编译?
最佳答案
如果您尝试从构造函数或析构函数进行虚函数调用,则可能会出现这种情况。由于您不能从构造函数或析构函数调用虚函数(派生类对象尚未构造或已被销毁),因此它调用基类版本,在纯虚函数的情况下,不会'不存在。
class Base
{
public:
Base() { reallyDoIt(); }
void reallyDoIt() { doIt(); } // DON'T DO THIS
virtual void doIt() = 0;
};
class Derived : public Base
{
void doIt() {}
};
int main(void)
{
Derived d; // This will cause "pure virtual function call" error
}
另见 Raymond Chen 的 2 articles on the subject
关于c++ - "pure virtual function call"崩溃从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/99552/