【发布时间】:2020-07-16 16:59:09
【问题描述】:
class CommandRoot {
protected:
string cmdString = "";
string title = "";
string tags = "";
string description = "";
public:
string getCmdString() {
return cmdString;
}
string getTitle() {
return title;
}
string getTags() {
return tags;
}
string getDescription() {
return description;
}
virtual bool onTrigger() {
return 1;
}
};
class CmdFirst : public CommandRoot{
public:
CmdFirst() {
cmdString = "testing1";
title = "";
tags = "";
description = "";
}
bool onTrigger() {
cout << "C";
return 0;
}
};
class Player {
NPC *target = NULL;
CommandRoot *cmdList[1];
public:
Player() {
cmdList[0] = new CmdFirst();
}
CommandRoot getCmdList(int n) {
return *cmdList[n];
}
NPC getTarget() {
return *target;
}
bool setTarget(NPC* t) {
target = t;
return 0;
}
string listen() {
string cmd = "";
cin >> cmd;
return cmd;
}
};
int main()
{
std::cout << "Hello World!\n";
Player* player = new Player();
NPC* firstNPC = new NPC();
player->setTarget(firstNPC);
bool exit = false;
do {
if (player->listen().compare(player->getCmdList(0).getCmdString()) == 0) {
cout << "A";
cout << player->getCmdList(0).onTrigger();
}
else
{
cout << "B";
}
} while (exit == false);
}
下面这行是调用父类的虚函数而不是派生类。
cout << player->getCmdList(0).onTrigger();
我有一种感觉,因为数组的数据类型是父类,但这不应该阻止数组元素被分配派生类的数据类型,然后调用该类的函数。
【问题讨论】:
标签: c++ function oop inheritance overloading