我可以递归调用每个基类中的方法而无需手动输入base :: Method()吗?

Jan*_*ser 3 c++ polymorphism

内容

  • 这个问题
  • 我为什么需要它

你好.

这个问题

我正面临一个问题.我有一个A类,它有一个基数B(是多态的).在B类中是方法Print(),它是虚拟的.在A类中也是Print().虚拟.假设我给了一个A类型的对象(或指针),存储在B变量中

B * object = new A(); 
Run Code Online (Sandbox Code Playgroud)

并通过电话

object->Print();
Run Code Online (Sandbox Code Playgroud)

它调用A类中的方法,但我也希望它在B类中调用方法.从技术上讲, 我想为每个孩子调用方法,直到我到达没有孩子的班级 这可以按如下方式完成:

class A
{
   public:
      virtual void Print() const override
      {
          cout << "A" << endl;
      }
};
class B : public A
{
   public:
      virtual void Print() const override
      {
         cout << "B" << endl;
         A::Print();     // i do not want to call it here...
      }
};
Run Code Online (Sandbox Code Playgroud)

问题是我确实不想被迫打电话给

A::Print();
Run Code Online (Sandbox Code Playgroud)

为什么

是的,你可能会问,交易是什么......我有很长的继承链.(假设继承链中有15-20个类).在游戏中,每个人都做一些小事.

让我们说

 class GameObject
    {
       public:
          virtual void Update() const
          {
              //updates position, recounts it towards screen
          }
    };
    class Character : public GameObject
    {
       public:
          virtual void Update() const override
          {
             // Updates lives, movement
          }
    };
    class Warrior : public Character
    {
       public:
          virtual void Update() const override
          {
             // Updates armor, specific stuff
          }
    };
Run Code Online (Sandbox Code Playgroud)

现在这个例子非常简单.问题是,如果我忘记添加一个调用基地:: Update()那么我很烦,为什么它不起作用.寻找这样的错误很难.我的意思是,如果有什么办法吗?

非常感谢您的回复.

祝你今天愉快

Pau*_*zie 5

如果确实每个类都必须调用基函数,那么确保强制执行功能的一种方法是使用模板模式.

class GameObject
{

   public:
      void Updater()
      {
         Update();  // this is a virtual call
         GameObject::Update(); // now call base 
      }

      virtual void Update() const
      {
      }
};

class Character : public GameObject
{
   public:
      virtual void Update() const override
      {
         // Updates lives, movement
      }
};

class Warrior : public Character
{
   public:
      virtual void Update() const override
      {
         // Updates armor, specific stuff
      }
};

class Character : public GameObject
{
   public:
      virtual void Update() const override
      {
         // Updates lives, movement
      }
};

class Warrior : public Character
{
   public:
      virtual void Update() const override
      {
         // Updates armor, specific stuff
      }
};
Run Code Online (Sandbox Code Playgroud)

然后总是打电话YourObject::Updater();而不是YourObject::Update().该Updater函数将调用对象的Update函数,然后返回并调用基类Update.