Problem overridding virtual function

后端 未结 3 1833
灰色年华
灰色年华 2020-12-21 10:41

Okay, I\'m writing a game that has a vector of a pairent class (enemy) that s going to be filled with children classes (goomba, koopa, boss1) and I need to make it so when I

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-21 11:31

    You need to call the parent's update method before any processing by the descendant classes:

    struct Base_Class
    {
      virtual void update(void)
      {
        cout << "Updating Base_Class.\n";
      }
    };
    
    struct Goomba : public Base_Class
    {
      void update(void)
      {
         // Invoke the parent method first.
         Base_Class::update();
    
         // Perform Descendant operations
         cout << "Updating Goomba\n";
      }
    };
    

    Here is the implementation:

    #include 
    using std::cout;
    
    void Update_Player(Base_Class& b)
    {
      b.update();
      return;
    }
    
    int main(void)
    {
       Goomba g;
       g.update();
    
       Goomba g2;
       std::vector container;
       container.push_back(&g);
       container.push_back(&g2);
    
       std::vector::iterator iter;
       for (iter =  container.begin();
            iter != container.end();
            ++iter)
       {
           Update_Player(*(*iter));
       }
    
       return 0;
    }
    

提交回复
热议问题