【发布时间】:2016-04-12 12:05:57
【问题描述】:
我的代码有一个简单的版本:
class Action:
{
int updateOK() {
std::cout << "" << std::endl;
return 0;
}
}
class Attack:public Action
{
int updateOK() {
std::cout << "att" << std::endl;
return 0;
}
}
class Def:public Action
{
int updateOK() {
std::cout << "DEf" << std::endl;
return 0;
}
}
namespace actions
{
const Attack light = Attack();
const Attack meduim = Attack();
const Attack heavy = Attack();
const Block block = Block();
const Block cancelBlock = Block();
const std::vector<Action> listAction = { light , meduim, heavy , block, cancelBlock };
}
Main.cpp :
for each (Action action in actions::listAction) {
action.updateOK();
}
问题是它总是在主函数中调用父函数。
我在很多方面都尝试过虚函数,但我想找到一个不使用强制转换的问题的解决方案。
有可能吗?
【问题讨论】:
-
提示。关键字覆盖是你最好的朋友:-)
-
没有演员表是什么意思?在父函数之前添加
virtual似乎是无需重大更改的方式。 -
@aybassiony 好吧,你还需要使用指针,当你使用它们时,你会得到从派生类到基类指针的隐式转换。
-
所以我必须制作一个指针列表,如 const std::vector
listAction
标签: c++