【问题标题】:Can the constructor of a derived class have more parameters than the constructor of its base class?派生类的构造函数可以比其基类的构造函数有更多的参数吗?
【发布时间】:2019-01-14 12:22:03
【问题描述】:

我有一个基类和两个派生类。基类有一些简单的受保护的浮点变量,我的基类的构造函数如下:

public Enemy(float _maxhp, float _damage)
{
    maxhp = _maxhp;
    health = _maxhp;
    damage = _damage;
}

但是,我的派生类 Range 还有 2 个浮点变量 attack and attackSpeed 在创建 Range 的新实例时需要作为参数传入,但我似乎无法做到这一点,因为当我尝试使用带有这些参数的派生类的构造函数时,错误提示 There is no argument that corresponds to the required formal parameter '_maxhp' of 'Enemy.Enemy(float, float)'

public Range(float _maxhp, float _damage, float _attack, float _attackSpeed)

但是具有相同数量参数的构造函数可以工作

public Range(float _maxhp, float _damage)

为什么会发生这种情况,是否有某种解决方法?提前致谢。

【问题讨论】:

  • 当然。所有对象都继承自没有构造函数参数的对象,因此某些对象具有多个参数的构造函数这一事实证明这是可以做到的。 (如果基类没有无参数构造函数,则只需将其链接到 base(...)。
  • 事实上,派生类的构造函数中的参数甚至可以更少,只要它向基构造函数传递一些东西。
  • 您能举个例子吗? @juharr
  • 考虑从矩形派生的正方形。 Rect 有两个参数 height 和 width 但 Square 有一个。
  • 另外,如果我的基本构造函数没有参数,但它做了一些事情,我希望我的派生构造函数也调用它,我只是将public Range() : base() 作为派生类的构造函数还是不需要吗?

标签: c# class unity3d constructor


【解决方案1】:

您必须指定如何使用base() 构造函数调用在基类上调用构造函数:

public Range(float _maxhp, float _damage, float _attack, float _attackSpeed)
    : base(_maxhp, _damage)
{
    // handle _attack and _attackSpeed
}

【讨论】:

    【解决方案2】:

    试试这个-

    public Range(float _maxhp, float _damage, float _attack, float _attackSpeed) : base(_maxhp, _damage)
    {
    this.attack = _attack;
    this.attackSpeed = _attackSpeed;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-16
      • 1970-01-01
      • 2016-07-19
      • 2021-02-14
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 2014-11-17
      相关资源
      最近更新 更多