C ++函数覆盖不起作用? [英] C++ Function Overriding not working?

查看:80
本文介绍了C ++函数覆盖不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一项任务开发游戏,但遇到了C ++中的函数覆盖问题.

I'm working on a game for an assignment and I've ran into an issue with function overriding in C++.

我具有以下结构:

class GameEntity
{
public:
    bool GameEntity::TakeHit(int dmg);
};

class Enemy : public GameEntity
{
    bool Enemy::TakeHit(int dmg);
};

当从另一个类中创建一个敌人的实例时,将其存储在GameEntity向量中,然后在其上调用TakeHit(),这就是在调用它的GameEntity版本.我已经习惯了在Java中将其称为其他版本,在这里我做错了什么吗?

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.

推荐答案

您需要通过virtual关键字声明可重写的方法. 正如评论中指出的那样,在类定义内添加类名限定符不是有效的C ++(但某些扩展名允许,例如MSVC ++ =).

You need to declare methods to be overridable via the virtual keyword. 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
};

这篇关于C ++函数覆盖不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆