[英]C++ how to call method in derived class from base class
What I want to do is for Execute()
to run and completes it calls the Base::Done()
then calls the Derived::Done()
. 我想要做的是让
Execute()
运行并完成它调用Base::Done()
然后调用Derived::Done()
。 I'm doing this because Base
class Execute
will do something and when its done call the Derived::Done()
. 我这样做是因为
Base
类Execute
会做一些事情,当它完成时调用Derived::Done()
。 I hope I'm explaining it correctly. 我希望我能正确解释。 Kind of like a listener that is called when a task completed.
有点像任务完成时调用的监听器。 I'm kinda stuck on how the
Base
class will call the Derived
class. 我有点坚持
Base
类将如何调用Derived
类。
class Base
{
virtual void Done(int code){};
void Execute();
}
void Base::Execute()
{
}
class Derived : Base
{
void Done(int code);
void Run();
}
Derived::Done(int code)
{
}
void Derived::Run()
{
Execute();
}
You can use a template method: 您可以使用模板方法:
class Base
{
public:
void Execute()
{
BaseDone(42);
DoDone(42);
}
private:
void BaseDone(int code){};
virtual void DoDone(int) = 0;
};
class Derived : Base
{
public:
void Run() { Execute(); }
private:
void DoDone(int code) { .... }
};
Here, Base
controls how its own and derived methods are used in Execute()
, and the derived types only have to implement one component of that implementation via a private virtual method DoDone()
. 这里,
Base
控制如何在Execute()
中使用自己的派生方法和派生方法,派生类型只需要通过私有虚方法DoDone()
实现该实现的一个组件。
The base class method can call the derived method quite simply: 基类方法可以非常简单地调用派生方法:
void Base::Execute()
{
Done(42);
}
To have the base class Done() called before the derived class, you can either call it as the first statement in the derived class method, or use the non-virtual idiom. 要在派生类之前调用基类Done(),可以将其作为派生类方法中的第一个语句调用,或者使用非虚拟习语。
Here's an example of calling it at the top of the derived class method. 这是在派生类方法的顶部调用它的示例。 This relies on the derived class to get it right.
这依赖于派生类来使其正确。
void Derived::Done(int code)
{
Base::Done(code);
}
Here's an example of using the non-virtual idiom: 以下是使用非虚拟习语的示例:
class Base
{
void Done(int code){
// Do whatever
DoneImpl(); // Do derived work.
}
virtual void DoneImpl() { };
...
};
class Derived {
virtual void DoneImpl() {
// Do derived class work.
};
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.