Inheritance and the base constructor

So, I'm trying to teach myself programming, and I'm doing a battle in the ring for practice. (basically just a very simple old RPG combat system in C #). However, I'm a little confused about inheritance. So, I have an Enemy base class:

class Enemy
{
    public string name;
    public int health;
    public int attack;
    public int level;

    public Enemy(string _name, int _health, int _attack, int _level)
    {
        name = _name;
        health = _health;
        attack = _attack;
        level = _level;
    }
}

And then I have this class Dragon:

class Dragon : Enemy
{

}

Why is it said that

there is no argument corresponding to the required formal parameter '_name' from 'Enemy.Enemy (string, int, int, int)?

My thought was that he would use the opponent’s constructor. Should I make each derived class my own constructor?

+4
source share
4 answers

: . , , , .

, , (, ). , , , .

-

public Dragon(string _name, int _health, int _attack, int _level)
  :base(_name, _health, _attack, _level)
{
}

. , ( ) Dragon. ( Dragon ).

public Dragon(string _name)
  :base(_name, 1000, 500, 10)
{
}

- .

+7

, , :

class Enemy
{
    public string name;
    public int health;
    public int attack;
    public int level;

    public Enemy(string _name, int _health, int _attack, int _level)
    {
        name = _name;
        health = _health;
        attack = _attack;
        level = _level;
    }

    protected Enemy()
    {

    }
}

:

public Dragon(string _name, int _health, int _attack, int _level) 
 : base(_name, _health, _attack, _level)
{
}
+3

, Dragon. , :

public Dragon() : base("test", 1, 1, 1){}

.

+2

, . Dragon Enemy?

Dragon, base, Dragon-Constructor . :

class Dragon : Enemy 
{
    public Dragon(string _name, int _health, int _attack, int _level) : base (_name, _health, _attack, _level)
    {

    }
}

You can even add some additional parameter to the constructor of your "dragon'-Class", which you do not need to pass to the base-Constructor, for example:

class Dragon : Enemy 
{
    public string DragonStuff { get; private set } 

    public Dragon(string _name, int _health, int _attack, int _level, string _dragonStuff) : base (_name, _health, _attack, _level)
    {
         DragonStuff = _dragonStuff;
    }
}
+1
source

Source: https://habr.com/ru/post/1679289/


All Articles