Constructing derived class from inherited variables

前端 未结 3 884
清酒与你
清酒与你 2021-01-21 08:23

Perhaps the title is a bit confusing so I\'ll try my very best to make sure it\'s as clear as possible.

Basically, I\'m trying to create a game where there is a abstract

3条回答
  •  醉酒成梦
    2021-01-21 08:44

    You can create a constructor in base class that takes str and armor as parameters and then pass them to the base constructor in the constructor of the derived class.

    class Creature
    {
      public:
        Creature(int a, int s) : armor(a), strength(s) {};
    
    protected:
        int armor;
        int strength;
    };
    
    class Human: public Creature
    {
       public:
          Human(int a, int s) : Creature(a, s) {}
    };
    

    Note: you can make Creature constructor protected if you want only the derived classes to construct a Creature.

    If you want to access armor and str values you will have to add getter functions, since armor and strength are protected member variables.

    class Creature
    {
      public:
        Creature(int a, int s) : m_armor(a), m_strength(s) {};
    
        int armor() const     { return m_armor; }
        int strength() const  { return m_strength; }
    
    protected:
        int m_armor;
        int m_strength;
    };
    

    Now you can have your main() function:

    int main() 
    { 
      Human Male(30, 50);
      cout << Male.armor();
      cout << Male.strength();
      return 0;
    }
    

提交回复
热议问题