CONTEXT
我正在开发一个战舰游戏,其中有一个游戏类,其中将有两个玩家相关联。付款人可能是Human
,或者Computer
处于不同的难度级别。但是,由于计算机和人类都是玩家,具有相同的方法,我想出了使用继承的想法。看起来很棒,但不是在实践中。
这是一个很大但可读性可重复的例子
[/ *代码创建了四个类:播放器,人类,计算机,游戏。 人类和计算机实现自己的游戏方法,游戏将接收两种类型的玩家作为参数。 / *]
#include <iostream>
#include <string>
class Player
{
std::string Name;
public:
Player(std::string myname):Name(myname){};
~Player(){};
virtual int play() = 0;
std::string name()
{
return Name;
};
};
class Human: public Player
{
public:
Human(std::string myname ):Player(myname){};
~Human(){};
int play()
{
return 1;
}
std::string name()
{
return Player::name();
}
};
class Computer: public Player
{
public:
Computer(std::string myname = "computer"):Player(myname){};
~Computer(){};
int play()
{
return 2;
}
std::string name()
{
return Player::name();
}
};
class Game
{
public:
Player p1;
Player p2;
Game(Player myp1, Player myp2):p1(myp1), p2(myp2){};
~Game(){};
void newTurn()
{
std::cout << "P1 plays: " << p1.play()
<< "\nP2 plays: " << p2.play();
}
};
int main(int argc, char const *argv[])
{
Computer TheComputer;
Human TheHuman("Jack");
Game TheGame(TheComputer,TheHuman);
TheGame.newTurn();
return 0;
}
错误
您可以检查自己的编译器。但是,如果您现在没有任何访问权限,这是一个示例。示例,因为p1
被指控的错误属于p2
,但我只会从p1
导入错误。
teste.cpp:64:14: error: cannot declare parameter ‘myp1’ to be of abstract type ‘Player’
Game(Player myp1, Player myp2):p1(myp1), p2(myp2){};
^
teste.cpp:4:7: note: because the following virtual functions are pure within ‘Player’:
class Player
^
teste.cpp:11:14: note: virtual int Player::play()
virtual int play() = 0;
^
teste.cpp:61:9: error: cannot declare field ‘Game::p1’ to be of abstract type ‘Player’
Player p1;
^
teste.cpp: In function ‘int main(int, const char**)’:
teste.cpp:80:35: error: cannot allocate an object of abstract type ‘Player’
Game TheGame(TheComputer,TheHuman);
^
我做了什么
将此属性替换为引用似乎是问题的解决方案,因为它将负责实例化对象。因为错误仍然存在(稍微小一些),我知道这还不够
Player &p1; //<< if you copy and paste(line 63)
Player &p2; //<< if you copy and paste (line 64)