我的代码有一个简单的版本:
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();
}
问题是它总是在main中调用父函数。
我已经尝试过很多方面的虚函数,但是我想在没有强制转换的情况下找到问题的解决方案。
有可能吗?
答案 0 :(得分:0)
你要做的是对象切片:
将派生类对象分配给基类对象时会发生这种情况,派生类对象的其他属性会被切除以形成基类对象
答案 1 :(得分:0)
如果你不介意演员,你需要:
示例编辑:
class Action:
{
virtual int updateOK() {
std::cout << "" << std::endl;
return 0;
}
};
--- the rest of classes ---
namespace actions
{
const Action* light = new Attack();
const Action* meduim = new Attack();
const Action* heavy = new Attack();
const Action* block = new Block();
const Action* cancelBlock = new Block();
const std::vector<Action*> listAction { light , meduim, heavy , block, cancelBlock };
}
Main.cpp :
for(Action* action : actions::listAction) {
action->updateOK();
}