在C++中捕获未实现的纯虚拟

Dus*_*rea 0 c++ pure-virtual

据我所知,有一些条件可能无法在子类上实现纯虚方法,但可以在没有它的情况下调用子类,从而导致构建错误.

我无法模拟这个.有人对如何实现这一点有任何见解吗?我已经完成了一些搜索,但一直无法进行任何搜索.

mr_*_*org 6

它发生在基类的构造函数中调用虚函数时.

#include <iostream>

class Base
{
public:
    Base() { g();} 
    virtual ~Base() {}

    void g() { f(); }
    virtual void f() = 0;
};

class Derived : public Base
{
public:
    Derived() : Base() {}
    ~Derived() {}

    void f() { std::cout << "Derived f()" << std::endl; }
};

int main()
{
    Derived d; // here we have the call to the pure virtual function

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

主要问题是:当Derived构造一个对象时,该对象以a开头Base,然后Base::Base执行构造函数.由于对象仍然是a Base,因此调用f()(via g())调用Base::f而不调用Derived::f.在之后Base::Base的构造完成,对象,然后成为一个DerivedDerived::Derived构造运行.