【发布时间】:2019-05-05 13:23:20
【问题描述】:
我有一个抽象类 Player 及其子 AI 和 Human。在我的主要工作中,当我创建两个对象 Human 和 AI 时,它工作正常。但是一旦我将它们用作等待 Player 指针类型的函数中的参数,那么它们的类型就不再是 AI 和 Human,而是都是 Player 对象。
游戏.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();
};
游戏.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;
}
播放器.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 显示相同的结果。但第一个显示 Human,第二个显示 Player。我该如何处理?
编辑 1:添加 Player.hpp 文件。
【问题讨论】:
-
我相信有很多完全不相关的代码。请删除它并提供minimal reproducible example 重现您的问题。
-
我试图脱掉无用的东西。但我认为剩下的内容有助于理解。
-
请向我们展示标头 Player.hpp。我猜这些方法没有被声明为虚拟的。当基类中的方法被声明为virtual时,子类的方法通过基类的指针或引用来调用。
标签: c++ pointers inheritance