【发布时间】:2021-05-14 11:30:57
【问题描述】:
我是 C++ 的初学者,我正在尝试制作一个简单的命令行游戏。我有三个班级:
class DynamicEntity : public Entity { // Entity class has only int x, y variables and getters/setters
protected:
enum direction {RIGHT = 77, LEFT = 75, UP = 72, DOWN = 80};
public:
posWrap getNextPos(); // Returns the xy coordinates of the entity's next position in a struct called posWrap
};
class Player : public DynamicEntity {
private:
int wishdir;
public:
int ammoCount = 0;
posWrap getNextPos(); // Same concept as above, but takes input
};
class CollisionHandler {
public:
static char checkCollisions(DynamicEntity& dEntity); // Checks the next position of the entity for collisions and returns what it would collide with
static char checkCollisions(Player& player);
};
你看,我重载了checkCollisions 方法。并将DynamicEntity 版本定义为:
char CollisionHandler::checkCollisions(DynamicEntity& dEntity) {
int x = dEntity.getNextPos().x;
int y = dEntity.getNextPos().y;
return readChar(x, y);
}
getNextPos 函数的实现对于 Player 和 DynamicEntity 是不同的,因为第一个函数从玩家那里获取输入,而后者从程序中的其他位置获取命令。
我想知道是否可以将Player 类传递给checkCollisions 并在方法内部使用getNextPos 的Player 版本,而无需明确编写checkCollisions 的另一个定义。我认为这是可能的,因为Player 是DynamicEntity 的孩子。还是我对编译器的要求太高了?
如果您有任何其他建议、批评或更好的方法来做这件事,请告诉我。我正在尝试更深入地了解这些主题。提前致谢!
【问题讨论】:
-
"我想知道是否可以将
Player类传递给checkCollisions" - 你有没有尝试过这样做? -
一种显而易见的答案是使用虚函数,所以我对你的问题感到困惑。无论如何,作为这里的新用户,请使用tour 并阅读How to Ask。
标签: c++ overloading