问题
I'm working on a game for an assignment and I've ran into an issue with function overriding in C++.
I have the following structure:
class GameEntity
{
public:
bool GameEntity::TakeHit(int dmg);
};
class Enemy : public GameEntity
{
bool Enemy::TakeHit(int dmg);
};
When from another class I create an instance of an Enemy, store it in a GameEntity vector, then call TakeHit() on it, it's calling the GameEntity version of it. I'm used to Java where this would call the other version, am I doing something obviously wrong here?
Other questions don't really cover this so I've created my own.
It's probably something pretty simple I'm guessing, so apologies for the trouble.
回答1:
You need to declare methods to be overridable via the virtual
keyword.
EDIT: As pointed out in a comment, adding the classname qualifier inside the class definition is not valid C++ (but allowed by some extensions, such as in MSVC++=).
class GameEntity
{
public:
virtual bool TakeHit(int dmg); // Can be overriden in subclasses
};
class Enemy : public GameEntity
{
bool TakeHit(int dmg); // No need to write virtual again
};
来源:https://stackoverflow.com/questions/26573414/c-function-overriding-not-working