我有几个问题试图向下转换到另一个类访问该类的具体方法。这是我目前的课程方案:向下转换dynamic_cast和多态类不工作
游戏对象类:
class GameObject
{
...
}
敌对阶级:
#include "../GameObject.h"
class Enemy : public GameObject
{
Enemy(Type type);
virtual ~Enemy();
virtual int receiveDamage(int attack_points);
virtual void levelUp() = 0;
...
protected:
char *name_;
int level_;
int health_;
int max_health_;
int attack_;
int armor_;
}
SmallGoblin类:
#include "../Enemy.h"
class SmallGoblin : public Enemy
{
public:
SmallGoblin();
~SmallGoblin();
void levelUp();
}
在我的代码,我尝试做这个和每次抛出std :: bad_cast异常。
class Player : GameObject
{
...
virtual void attack(GameObject &enemy)
{
try
{
Enemy &e = dynamic_cast<Enemy&>(enemy);
e.receiveDamage(attack_points_);
}
catch(const std::bad_cast& e)
{
std::cerr << e.what() << '\n';
std::cerr << "This object is not of type Enemy\n";
}
}
...
}
(敌人是一个GameObject对象的引用,但是我知道它实际上是一个SmallGoblin对象)。
在其他部分我的代码我有anoother类(门),它扩展了GameObject类和向下转换工作(但是,我必须使用static_cast而不是dynamic_cast,我不知道为什么)。
你能提供一个SSCCE吗? – chris 2013-04-28 21:21:10
我会用我真实的代码更新这个问题。 – Puyover 2013-04-28 21:21:49
如果你不得不使用'static_cast',你可能会得到未定义的行为。 – 2013-04-28 21:23:05