C++ 从父常量对象调用子函数
我的代码有一个简单的版本:C++ 从父常量对象调用子函数,c++,C++,我的代码有一个简单的版本: class Action: { int updateOK() { std::cout << "" << std::endl; return 0; } } class Attack:public Action { int updateOK() { std::cout <&l
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();
}
集体诉讼:
{
int updateOK(){
std::cout您试图做的是对象切片:
当派生类对象被指定给基类对象时,会发生这种情况,派生类对象的附加属性会被切掉以形成基类对象,如果您不介意,则需要:
- 使父函数为虚拟函数,以便动态绑定工作
- 如果需要使用泛型容器,则需要使用指向基类的指针作为对象
编辑示例:
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();
}
集体诉讼:
{
虚拟int updateOK(){
std::您是否需要重新访问提示。关键字override在这里是您最好的朋友:-)没有强制转换是什么意思?在父函数之前添加virtual
似乎是一种不做重大更改的方法。@aybassiouny您还需要使用指针,当您使用它们时,您将得到从派生类到基类的隐式强制转换s指针。因此我必须创建一个指针列表,如const std::vector ListActionThank我会用谷歌搜索它;)如果你想获得想要的结果,请使用多态性。我以前尝试过它,但问题是它给了我一个“错误:无法从“Action*const”转换为“Action”`