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