【问题标题】:How to use abstract class' children instances through methods?如何通过方法使用抽象类的子实例?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 我不明白。我的目标只是将 Game 类中的变量 j1 设置为 Human,因为它是一个子类。
  • upAge() 呢?是Player的虚函数吧?
  • 您希望两个 cout 的 typeid 结果必须相同。为此,基类,即 Player 不得包含虚函数。请移除基础中的虚函数。
猜你喜欢
  • 2015-10-06
  • 2021-01-10
  • 1970-01-01
  • 2019-02-11
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
相关资源
最近更新 更多