我正在尝试编写一个名为TerminalPlayer的派生类,该派生类继承了一个类Player,给定虚拟const Card playCard(const Card opponentCard(=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
}
测试.cpp
int main(){
// This initialization give error: cannot allocate an object of abstract type ‘Player’
TerminalPlayer player1 = Player("Player1");
return 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限定符是不必要的,因为您是按值返回的。