施工后立即调用虚拟方法

Var*_*gas 5 c++ inheritance

我需要在构造派生对象之后立即为从给定基类派生的所有类调用虚方法.但是在基类构造函数中执行此操作将导致纯虚方法调用

这是一个简化的例子:

struct Loader {
    int get(int index) { return 0; }
};

struct Base{
    Base() {
        Loader l; 
        load( l ); // <-- pure virtual call!
    }
    virtual void load( Loader & ) = 0;
};

struct Derived: public Base {
    int value;
    void load( Loader &l ) {
        value = Loader.get(0);
    }
};
Run Code Online (Sandbox Code Playgroud)

我可以loadDerived构造函数中调用,但Derived不知道如何创建一个Loader.任何想法/解决方法?

Goz*_*Goz 6

问题是基类构造发生在完全构造派生类之前.您应该从派生类调用"load",初始化throguh不同的虚拟成员函数或创建一个帮助函数来执行此操作:

Base* CreateDerived()
{
    Base* pRet = new Derived;
    pRet->Load();
    return pRet;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ork 2

使用 PIMPL 模式:

template<typename T>
class Pimpl
{
    public:
        Pimpl()
        {
            // At this point the object you have created is fully constructed.
            // So now you can call the virtual method on it.
            object.load();
        }
        T* operator->()
        {
            // Use the pointer notation to get access to your object
            // and its members.
            return &object;
        }
    private:
        T    object;   // Not technically a pointer
                       // But otherwise the pattern is the same.
                       // Modify to your needs.
};

int main()
{
    Pimpl<Derived>   x;
    x->doStuff();
}
Run Code Online (Sandbox Code Playgroud)