如何通过方法使用抽象类的子实例?

时间:2019-05-05 13:23:21

标签: c++ pointers inheritance

我有一个抽象类的Player及其子AI和Human。总的来说,当我创建两个对象Human和AI时,它可以很好地工作。但是一旦在等待播放器指针类型的函数中将它们用作参数时,它们的类型就不再是AI和Human,而是两者都是Player对象。

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 :(得分:0)

基类Player必须包含一个虚函数才能将类型名称作为派生类。

从cpp参考中检查以下示例中的typeid

#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