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

How to use abstract class' children instances through methods?

本文关键字:实例 抽象类 何通过 方法      更新时间:2023-10-16

我有一个抽象的班级玩家及其孩子AI和人。在我的主要位置,当我创建两个人类和AI时,它可以正常工作。但是,一旦我将它们用作等待播放器指针类型的函数中的参数,那么它们的类型不再是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;
}

我希望两个cout显示相同的结果。但是第一个显示人类,第二个显示播放器。我该如何处理?

编辑1:添加player.hpp文件。

基类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