如何通过方法使用抽象类的子实例?
How to use abstract class' children instances through methods?
我有一个抽象的班级玩家及其孩子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
相关文章:
- 无法创建抽象类的实例
- ATL::CComContainedObject<contained>: C2259 无法实例化抽象类
- 如何使用其中一个具体类实例化抽象类?
- 无法实例化抽象类错误
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- C++的研究案例.抽象类和实例
- 'AMA::我的产品':无法实例化抽象类
- 如何在代码中创建抽象类,让蓝图扩展它,并将该蓝图返回给代码进行实例化?
- 无法实例化抽象类
- 如何修复错误C2259:无法实例化抽象类
- 如何通过方法使用抽象类的子实例?
- C++,不能实例化抽象类
- 从抽象类继承的类的实例
- 无法使用多重继承 c++ 实例化抽象类
- 无法实例化抽象类
- 纯抽象类和派生类型的实例化
- 如何在派生实例化之前创建抽象类
- 使用std :: make_shared抽象类实例化的错误
- C++,无法实例化抽象类错误
- C2259:'ATL::CComObject<Base>':无法实例化抽象类