Как использовать дочерние экземпляры абстрактного класса через методы? - PullRequest
0 голосов
/ 05 мая 2019

У меня есть абстрактный класс Player и его дети AI и Human.В основном, когда я создаю два объекта, Human и AI, все работает нормально.Но как только я использую их в качестве параметров в функции, которая ожидает тип указателя Игрока, их тип больше не будет ИИ и Человеком, но оба являются объектами Игрока.

Game.hpp:

#include "Player.hpp"
#include "Human.hpp"

class Game {
private:
    Player *j1, *j2;

public:
    Game();
    Game(Player*, Player*);
    void setP1(Player*);
    void setP2(Player*);
    Player* getP1();
    Player* getP2();
};

Game.cpp:

 #include "Game.hpp"

 Game::Game(){

}

Game::Game(Player *pp1, Player *pp2){
p1 = pp1;
p2 = pp2;
}

void Game::setP1(Player *pp1){
p1 = pp1;
}

void Game::setP2(Player *pp2){
p2 = pp2;
}

Player* Game::getP1(){
return p1;
}

Player* Game::getP2(){
return p2;
}

Player.hpp:

#ifndef PLAYER_H
#define PLAYER_H
#include <string>

using std::string;

class Player {
protected:
    string nom;
    int age;

public:
    Player();
    Player(string, int);
    void setNom(string);
    void setAge(int);
    string getNom();
    int getAge();

    virtual void upAge() = 0;
};

#endif

Вот main.cpp:

#include "Player.hpp"
#include "Human.hpp"
#include "Game.hpp"

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int main(){
Player *j;
Human h;
Game Game;

cout << typeid(h).name() << endl;
Game.setJ1(&h);
cout << typeid(Game.getJ1()).name() << endl;



return 0;
}

Я хотел бы два кутотображать тот же результат.Но первый отображает человека, а второй - игрока.Как я могу справиться с этим?

РЕДАКТИРОВАТЬ 1: добавлен файл Player.hpp.

1 Ответ

0 голосов
/ 05 мая 2019

Базовый класс Player должен содержать виртуальную функцию для получения имени типа в качестве производного класса.

check typeid ниже пример из ссылки cpp.

#include <iostream>
#include <string>
#include <typeinfo>

struct Base {}; // non-polymorphic
struct Derived : Base {};

struct Base2 { virtual void foo() {} }; // polymorphic
struct Derived2 : Base2 {};

int main() {

    // Non-polymorphic lvalue is a static type
    Derived d1;
    Base& b1 = d1;
    std::cout << "reference to non-polymorphic base: " << typeid(b1).name() << '\n';

    Derived2 d2;
    Base2& b2 = d2;
    std::cout << "reference to polymorphic base: " << typeid(b2).name() << '\n';
 }

Возможный вывод:

reference to non-polymorphic base: 4Base
reference to polymorphic base: 8Derived2
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...