clase - Problemas del constructor de herencia de C++

CorePress2024-01-24  11

He creado 2 clases (Entidad y Jugador).

Básicamente, la clase Player hereda de la clase Entidad, por lo que una instancia de Player es en sí misma un objeto Entidad.

Aquí está la primera clase:

#include <iostream>

#define print(obj) std::cout << obj << std::endl

class Entity {
    public:
        int xPos, yPos;

    Entity(int xInitPos, int yInitPos) {
        xPos = xInitPos;
        yPos = yInitPos;
    }

    void move(int _x, int _y) {
        xPos += _x;
        yPos += _y;
    }
};

El jugador de segunda clase necesita tener algunos datos adicionales:

int healt;
int level;

Aquí está la parte en la que me confundí. No sé si debo especificar un nuevo constructor para esta clase porque necesita obtener 2 parámetros adicionales.

Esto es lo que hice hasta ahora:

class Player : public Entity {
    public:
        int healt;
        int level;
// I know that this piece of code is wrong
    Player(int _level, int _healt) {
        level = _level;
        healt = _healt;
    }
};

Soy nuevo en la programación en C++ y no sé cómo funciona la herencia, tampoco sé cómo crear entidades de la clase Player y cuáles son los parámetros que necesita.

Aquí está la función principal:

int main() {  
    
    Entity ent1 = Entity(0, 0);
    ent1.move(4, 8);

    Player player = Player(what attributes);

    return 0;
}

1

Puedes llamar al constructor base en el constructor secundario, p.e. Player(int _level, int _health): Entidad(0, 0), nivel(_level), salud(_health) {} Y como ves, uso 0, 0 para el constructor de Entidad. Entonces, si quisiera especificar la posición, tendría que ajustar el constructor de mi Reproductor para que también acepte las posiciones x e y: Jugador(int _level, int _health, int x, int y): Entidad(x, y), nivel(_level) , salud(_salud) {}

- Philipp

27/03/2021 a las 20:41



------------------------------------

Como no tienes un constructor predeterminado para Entity que no acepte argumentos, también debes inicializarlo:

Player(int _level, int _healt) : Entity(0 , 0) {
    level = _level;
    healt = _healt;
}

O más idiomáticamente:

Player(int _level, int _healt) : Entity(0 , 0), healt(_healt), level(_level) {}

En el ejemplo anterior, inicializo de forma predeterminada ambas posiciones con 0. Si desea proporcionar los valores de posición usted mismo, deberá tener un constructor que también tome estos valores:

Player(int _level, int _healt, int posX, int posY) 
       : Entity(posX , posY), healt(_healt), level(_level) {}

Y llámalo así:

Player player = Player(1, 100, 0, 0);



------------------------------------

Aquí hay un ejemplo de cómo podría verse:

#include <iostream>

class Entity {
    public:
        int xPos, yPos;

    Entity(int xInitPos, int yInitPos) {
        xPos = xInitPos;
        yPos = yInitPos;
    }

    void move(int _x, int _y) {
        xPos += _x;
        yPos += _y;
    }
};

class Player : public Entity {
    public:
        int health;
        int level;
// Constructor that also accepts x and y which are passed on to the base constructor
// The syntax with the : and , separated values is a initializer list.
    Player(int x, int y, int _level, int _health)
    : Entity(x, y)
    , level(_level)
    , health(_health) {}

// Constructor without x and y, passing 0 for x and y to the base constructor
    Player(int _level, int _health)
    : Entity(0,0)
    , level(_level)
    , health(_health) {}
};

int main() {
    Player p(2, 3, 1, 100); // Creates a player at position (2,3) with level 1 and 100 health
    Player p2(2, 110); // Creates a player at position (0,0) and level 2 and 110 health
    std::cout << p.xPos << '\n';
}

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare