非虚拟接口 - 如何调用正确的虚函数

Ton*_*ion 0 c++ polymorphism virtual non-virtual-interface

我的层次结构看起来像这样:

class Base
{
public:
    void Execute();
    virtual void DoSomething() = 0;
private:
    virtual void exec_();
};

class Derived : public Base
{
public:
   //DoSomething is implementation specific for classes Derived from Base
   void DoSomething();

private:
    void exec_();
};

void Base::Execute()
{
    // do some work 
    exec_();  //work specific for derived impl
    // do some other work
}

void Derived::DoSomething()
{
   //impl dependent so it can only be virtual in Base
}


int main()
{
  Derived d;
  Base& b = d;

  b.Execute();  //linker error cause Derived has no Execute() function??

}
Run Code Online (Sandbox Code Playgroud)

所以问题是当我使用我的Base类创建派生时,如何使用此模式调用Execute().在我的情况下,我不想直接创建Derived,因为我有从Base派生的多个类,并且根据某些条件,我必须选择不同的派生类.

有人可以帮忙吗?

sbi*_*sbi 6

这个

class Base
{
public:
    void Execute();
private:
    virtual void exec_() {}
};

class Derived : public Base
{
private:
    void exec_() {}
};

void Base::Execute()
{
    // do some work 
    exec_();  //work specific for derived impl
    // do some other work
}

int main()
{
    Derived d;
    Base& b = d;

    b.Execute();
}
Run Code Online (Sandbox Code Playgroud)

为我编译,链接和运行.