наследование — C ++, реализующий абстрактные классы

Я пытаюсь написать производный класс с именем TerminalPlayer, который наследует класс Player при объявлении виртуальной const Card playCard (const Card оппозиционная карта) = 0; как бы вы реализовали унаследованную playCard в абстрактном классе и что означает = 0 в конце прототипа?

У меня также есть ошибка в основном тестовом коде, которая выдает ошибку: не удается выделить объект абстрактного типа «Player». Я думаю, что это потому, что я не реализую класс Player правильно, но я не знаю, как это исправить.

Player.h

    #ifndef PLAYER_H_
#define PLAYER_H_

#include <vector>
#include "Card.h"
#define MAX_HAND_SIZE 3

// Abstract Player classS
class Player {

public:
// Deconstructor
virtual ~Player() {
}

// Play a card. If the player receives a joker then this player is going first
virtual const Card playCard(const Card opponentCard) = 0;

// Receive a card from the dealer
void receiveCard(const Card c) {
hand.push_back(c);
}

// Add points to the score
void addScore(unsigned s) {
score += s;
}

// Get the score
int getScore() const {
return score;
}

// Return true if the player has cards in the hand
bool hasCards() const {
return (hand.size() != 0);
}

// Receive the cards played from the previous round. This member function would be used by a computer player that may need to 'see' what cards were played.
void cardsPlayed(const Card card1, const Card card2) {

}

// Output the players name
friend std::ostream& operator <<(std::ostream& out, const Player& p);

protected:
// Constructor. Since this is an abstract class we do not want anyone instantiating a player class so we make it protected.
Player(std::string name) :
score(0), name(name), hand(0) {
}

int score;
std::string name;
std::vector<Card> hand;
};

#endif

TerminalPlayer.h

    #ifndef TERMINALPLAYER_H_
#define TERMINALPLAYER_H_

#include "Player.h"
class TerminalPlayer : public Player {
public:
TerminalPlayer(std::string name);
virtual ~TerminalPlayer();
};

#endif

TerminalPlayer.cpp

    #include "Player.h"Card playCard(const Card opponnentCard){
// TODO: playCard code here
}

test.cpp

    int main(){

// This initialization give error: cannot allocate an object of abstract type ‘Player’
TerminalPlayer player1 = Player("Player1");

return 0;
}

0

Решение

= 0' означает, что это pure virtual функция.
Этот тип функции должен быть определен любым классом, который наследуется от базового класса и создается в программе.

Поскольку ваш базовый класс объявляет:

// Play a card. If the player receives a joker then this player is going first
virtual const Card playCard(const Card opponentCard) = 0;

Вы должны реализовать эту функцию в своем производном классе.
Вы подходите близко к TerminalPlayer.cpp:

const Card TerminalPlayer::playCard(const Card opponnentCard){
// TODO: playCard code here
}

Что вы упускаете TerminalPlayer:: область видимости показана выше.
Также отсутствует объявление функции в производном классе. Вам нужно добавить:

virtual const Card playCard(const Card opponentCard) override;

В классе TerminalPlayer, Поместите это сразу после деструктора.

Это должно сделать это.

Одна мысль: квалификатор const в возвращаемом значении не нужен, так как вы возвращаете по значению.

3

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector