非虚拟接口 - 如何调用正确的虚拟函数
我有一个看起来像这样的层次结构:
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()。就我而言,我不想直接创建 Derived,因为我有多个从 Base 派生的类,并且根据某些条件我必须选择不同的派生类。
有人可以帮忙吗?
I have a hierarchy that looks something like this:
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??
}
So the question is how do I call Execute() using this pattern when I create a derived using my Base class. In my case I do not want to create Derived directly, as I have multiple classes derived from Base and depending on some condition I have to pick a different derived class.
can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可以
为我编译、链接和运行。
This
compiles, links, and runs for me.
您可能还应该在基类中将 exec_() 设为纯虚拟。然后,您还需要在派生类中实现它。
You should probably also make exec_() pure virtual in your base class. You then also need to implement it in your derived classes.
您需要为 exec_() 函数编写函数定义。
You need to write a function definition for exec_() function.