我有一个层次结构,看起来像这样:
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??
}
所以问题是,当我使用基类创建派生时,我如何使用这种模式调用Execute()。在我的例子中,我不想直接创建派生类,因为我有多个从Base派生的类,并且根据某些条件,我必须选择一个不同的派生类。
有人能帮忙吗?
This
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();
}
为我编译、链接和运行。
您可能还应该在基类中将exec_()设置为纯虚的。然后,您还需要在派生类中实现它。
您需要为exec_()函数编写一个函数定义