从继承的变量构造派生类 [英] Constructing derived class from inherited variables

查看:136
本文介绍了从继承的变量构造派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许标题有点混乱,所以我会尽我所能确保它尽可能清楚。

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

基本上,我想创建

现在我的问题是:

如果我有一个基类具有受保护的变量int strength和int armor,我如何使用int strength和int armor构造一个派生类,以便他们获得自己的值,而不需要实际定义强度和盔甲该类中的变量?

if I have a base class that has protected variables int strength and int armor, how can I construct a derived class using int strength and int armor so that they get their own value without actually defining strength and armor variables within that class?

让我编写我试图实现的代码。

Let me write the code that I'm trying to achieve.

class Creature
{
  public:
    Creature();
  private:
    int armor;
    int strength;
};

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

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

我该如何做?我需要有装甲和力量在第一类,所以我不能在每个派生类中声明它。

How would I do this? I need to have armor and strength within the first class so I can't declare it in every derived class.

任何帮助。谢谢!

推荐答案

您可以在基类中创建一个构造函数,将str和armor作为参数,然后传递给基础

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) {}
};

注意:您可以使 Creature code> protected 如果只想派生类构造一个 Creature

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

如果您要访问护甲和str值,您必须添加getter函数,因为护甲和力量是受保护的成员变量。

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;
};

现在你可以使用main()函数:

Now you can have your main() function:

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

这篇关于从继承的变量构造派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆