c++ - C++ 实现抽象类
问题描述
我正在尝试编写一个名为 TerminalPlayer 的派生类,它在给定虚拟 const Card playCard(const Card contrastCard) = 0; 的声明的情况下继承一个 Player 类 您将如何在抽象类中实现继承的 playCard 以及原型末尾的 = 0 是什么意思?
我在主要测试代码中也有错误,它给出了错误:无法分配抽象类型“播放器”的对象。我认为这是因为我没有正确实现 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
终端播放器.h
#ifndef TERMINALPLAYER_H_
#define TERMINALPLAYER_H_
#include "Player.h"
class TerminalPlayer : public Player {
public:
TerminalPlayer(std::string name);
virtual ~TerminalPlayer();
};
#endif
终端播放器.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 限定符不是必需的,因为您是按值返回的。
推荐阅读
- python - FitFailedWarning:估计器拟合失败。这些参数在这个训练测试分区上的分数将设置为 nan
- javascript - 如何在 ReactJS 中设置嵌套路由和嵌套组件
- javascript - 使用 React 使用预先存在的值预填充日期输入
- android - 嵌套滚动 Jetpack 组合
- c# - 如何在 Unity 编译器中修复“Unity CS0101”
- react-native - 如何用我对本机反应的看法创建一个波浪
- c++ - C++中如何判断一个整数类型是不是内置类型?
- verilog - 移位寄存器,将有线输入连接到内部寄存器
- python - Python,从还包含列表的大型嵌套字典中返回指定的键值
- tomcat - log4j2 错误导致 Tomcat 停止