编译器调用基类方法而不是子类方法



首先抱歉,代码是外文的

我有一个问题,当我编译下面的代码编译器调用基方法而不是子方法。

我有这个基类:

Jugador.h

#ifndef JUGADOR_H_
#define JUGADOR_H_
#include <iostream>
using namespace std;
class Jugador{
    protected:
        bool color;//true->rojo   false-> azul
    public:
        Jugador(bool rojo) { color = rojo; }
        Jugador() {}
        virtual string getInput();
        ~Jugador(){}
};
#endif

Jugador.cpp

#include "Jugador.h"
using namespace std;
string Jugador::getInput(){
cout<<"Is Called"<<endl;
}

这个子类:JugadorHumano.h

#ifndef JUGADORHUMANO_H_
#define JUGADORHUMANO_H_
#include <iostream>
#include <string>
#include "Jugador.h"
using namespace std;
class JugadorHumano: public Jugador {
    public:
        JugadorHumano(bool rojo) :Jugador(rojo) {}
        virtual string getInput();//Tested with override too
};
#endif

JugadorHumano.cpp

#include "JugadorHumano.h"
using namespace std;
string JugadorHumano::getInput(){
    string input;
    getline(cin, input);
    return input;
}

然后,在与这两个无关的第三个类方法上,我在使用它们之外做了:

Jugador rojo;
rojo=JugadorHumano(true);
rojo.getInput();

谢谢你的关注。

编辑:对不起,这是我的第一个问题,添加了cpp文件

Edit2:做了@Raindrop7建议的更改,现在编译但仍然调用基方法,它打印"Is Called"而不是做getline。

Edit3:谢谢

OLD:当编译器到达getInput时抛出一个错误"对'Jugador::getInput()'的引用未定义"。我不知道为什么会发生这种情况,也不知道如何修复它。

如果不想在基类(Jugador)中定义getInput(),那么您需要将其设置为纯虚拟

virtual string getInput()=0;

但是,您将无法实例化Jugador,因为它将成为一个抽象类,

Jugador rojo; // error tries to instantiate abstract class 
因此,在第三个类中需要创建JugadorHumano对象
Jugador * rojo = new JugadorHumano(true);
rojo->getInput();

最新更新