好吧,我来自 Java,目前正试图搞清楚 C++ 的东西。所以我一直在乱涂乱画,我有一个基本的 RPG 游戏类型的基本继承。 这是层次结构的概述:
Being (Base object that contains a pointer to a Race)
Race (Base Class)
-Elf (derived class)
-Human (derived class)
所以在我的 Being
构造函数中,我有以下代码:
int str,
intl,
wis,
dex,
HP,
tHP;
string name;
Race *race;
public:
//Send a reference to an object of a SUBCLASS of Race.
Being(string name, Race *r)
:name(name), race(r){
str = 10;
intl = 10;
wis = 10;
dex = 10;
tHP = 15;
HP = tHP;
race->applyStats(this);
}
当我说 race->applyStats(this)
时,我的问题就出现了。尽管从语法上讲这成功调用了 Race
的 applyStats
方法,但我希望它调用子类之一。例如,我有一个名为 Elf
的类,如下所示:
class Elf : public Race{
public:
Elf()
:Race("Elf"){
}
void applyStats(Being *being){
cout << "entered" <<endl;
being->setStr( being->getStr() - 2 );
being->setWis( being->getWis() + 2 );
being->setTHP( being->getTHP() - 2 );
}
};
主要是我运行这段代码:
Being b ("Tanis", new Elf());
//Don't worry about printStats(), it just lists the stats as the sample output shows
b.printStats();
示例输出:
-Tanis-
Race Elf
Strength 10
Intelligence 10
Wisdom 10
Dexterity 10
Health 15/15
是的。所以我不太明白,也许我只是太习惯了 Java,但是当我说 applyStats(this)
时,它不应该调用 applyStats()
属于 Elf 类
?
最佳答案
在类 Race 函数中,applyStats 必须声明为虚拟的。例如
virtual void applyStats( const Being *being) const;
(我稍微修改了它的声明)
也不要忘记将基类的析构函数也定义为虚拟的。
如果您只使用派生类的对象,您也可以将 Race 类定义为抽象类。例如
virtual void applyStats( const Being *being) const = 0;
关于C++ 从父指针访问子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23071824/