【发布时间】:2020-09-05 20:28:55
【问题描述】:
我正在尝试自己创建一个“外星入侵者”游戏。为了创建敌人和玩家,我创建了一个名为“实体”的类并创建了它的子类。比如 Player、shootingEnemy、IdleEnemy。编码时,我意识到将它们收集在 vector<Entity> 中会使我的碰撞检测功能更容易。
在互联网上搜索后,我了解到这称为“对象切片”,并复制对象的任何基本部分。
所以最终版本变成了这个。
int main()
{
int BoardWidth = 50;
int BoardLength = 30;
vector<Bullet> bullets;
vector<Entity*> SpaceShips;
setup(SpaceShips, BoardWidth, BoardLength);
double ElapsedTime = 0;
int PreviousRoundSec = 0;
int PreviousRoundQSec = 0;
DrawGame(BoardWidth, BoardLength, SpaceShips, bullets);
int IsGameOver = 0;
auto start = chrono::steady_clock::now();
while(!IsGameOver)
{
// Updates EverySecond
if ((int)(ElapsedTime / 1000) > PreviousRoundSec)
{
PreviousRoundSec = (int)(ElapsedTime / 1000);
}
// Updates every quarter of a second
if ((int)(ElapsedTime / 250) > PreviousRoundQSec)
{
PreviousRoundQSec = (int)(ElapsedTime / 250);
}
// To keep time
auto end = chrono::steady_clock::now();
ElapsedTime = chrono::duration_cast<chrono::milliseconds>(end - start).count();
}
if (IsGameOver == 1)
{
// conjualations
}
else if (IsGameOver == 2)
{
// GameOver
}
return 0;
}
但是当我尝试使用某些特定于子类的函数时,我收到一个编译器错误,提示“CLASS "Entity" 没有任何名为 "shoot" 的成员"。
我正在尝试练习类和多态性,所以我什至不知道这是否有解决方案,因为编译器无法知道该向量的哪个元素属于哪个子类。
这也是我的课程标题页,以备不时之需。
class Entity
{
public:
int x;
int y;
int width;
int length;
int hp;
bool shooting;
public:
Entity(int x, int y, int width, int length, int hp, bool shooting): x(x), y(y), width(width), length(length), hp(hp), shooting(shooting) {}
};
class Bullet : public Entity
{
private:
char dir;
int ID;
public:
Bullet(int x, int y, char GivenDir, int GivenID) : Entity(x, y, 1, 1, 1, false) { dir = GivenDir; ID = GivenID; }
void Move();
void IfHit(vector<Entity>& SpaceShips);
void IfOut();
};
class Player : public Entity
{
private:
char action = 'a';
public:
Player(int x, int y, int hp) : Entity(x, y, 3, 2, hp, true) {}
void GetAction();
void Move();
void Shoot(vector<Bullet>& bullets);
bool IfHit(vector<Entity>& SpaceShips, vector<Bullet>& bullets);
};
class IdleEnemy : public Entity
{
public:
IdleEnemy(int x, int y, int hp) : Entity(x, y, 3, 2, hp, false){}
bool IfHit(Player* player, vector<Bullet> &bullets);
void Move(char HordDir);
};
class ShootingEnemy : public Entity
{
public:
ShootingEnemy(int x, int y, int hp) : Entity(x, y, 3, 2, hp, true) {}
void Shoot(vector<Bullet> &bullets);
bool IfHit(Player* player, vector<Bullet> &bullets);
void Move(char HordDir);
};
【问题讨论】:
-
您可以将指针重新解释为子类指针以访问子类特定的函数。
-
我该怎么做呢?能给我举个小例子吗?
-
auto ptr = reinterpret_cast
(Spaceships[n]); -
那你应该可以做ptr->Shoot();
-
正如下面的答案所指出的,dynamic_cast 在这里比 reinterpret_cast 更好。
标签: c++ class polymorphism