从基类调用派生类函数

从基类调用派生类函数

本文介绍了从基类调用派生类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class base
{
  public:
  virtual void start();
  virtual void stop();

  void doSomething() { start(); .... stop(); }
}

class derived : public base
{
  public:
   void start();
   void stop();
}

但是当我打电话给 doSomething()在派生类中,它使用它自己定义的 Start() Stop() - 不是派生的。

But when I call doSomething() in the derived class it is using it's own definition of Start() and Stop() - not the derived ones.

我不想在派生类中重写 doSomething(),因为它与基数相同一。我做错了什么?

I don't want to rewrite doSomething() in the derived class because it would be identical to the base one. What am I doing wrong?

如果不清楚,请抱歉。

派生类中Start()和Stop()的行为是不同的(它是一个不同的机器) - 但我想使用原始基类doSomething(),因为它没有改变。它只需要使用新的派生类代码start()和stop()。

Sorry if that wasn't clear.
The behaviour of Start() and Stop() in the derived class is different (it's a different machine) - but I want to use the original base class doSomething() because that hasn't changed. It just has to start() and stop() using the new derived class code.

推荐答案

你发布的代码应该是以你想要的方式工作。在派生的实例上调用 doSomething 将调用重写的 start 停止派生的中定义的函数。

The code you've posted should work the way you want. Calling doSomething on an instance of derived will call the overridden start and stop functions defined in derived.

这里有但是,这是一个例外。如果在 base 的构造函数或析构函数中调用 doSomething (无论是直接还是间接),那么<$的版本c $ c> start 和 stop 被调用的将是 base 中定义的那些。那是因为在这种情况下,你实际上还没有一个有效的派生的实例。它要么没有完全构造,要么部分被破坏,因此语言会阻止你调用使用部分对象的方法。

There's an exception to that, though. If you call doSomething in the constructor or destructor of base (whether directly or indirectly), then the versions of start and stop that get called will be the ones defined in base. That's because in those circumstances, you don't actually have a valid derived instance yet. It's either not fully constructed or partially destructed, so the language prevents you from calling methods that would use the partial object.

如果你没有从<$中调用它c $ c> base 构造函数或析构函数,然后问题比这里显示的更多。

If you're not calling it from a base constructor or destructor, then there is more to the problem than what's shown here.

这篇关于从基类调用派生类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:54