C++ Function Overriding not working?

僤鯓⒐⒋嵵緔 提交于 2019-12-23 04:49:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!