2016-04-12 17 views
0

子功能还有就是我的一个简单的代码版本:调用从父常量对象

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(); 
    } 

的问题是,它总是调用主父功能。

我已经尝试了许多方式的虚拟功能,但我想找到解决方案的问题没有强制转换。

可能吗?

+2

您需要重新[多态性是如何工作的(http://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm) – NathanOliver

+0

提示。关键字覆盖是你最好的朋友在这里:-) – Thinkeye

+0

你是什么意思没有演员?在父功能之前添加虚拟似乎是没有重大改变的方式。 – aybassiouny

回答

0

你正在尝试做的是对象切片:

当一个派生类对象被分配到一个基类对象碰巧的是,一个派生类对象的附加属性被切掉而形成的基类对象

+0

谢谢我会google的;) –

+0

如果你想达到预期的效果,请使用多态。 –

0

如果你不介意的话蒙上你需要:

  • 制作父功能的虚拟动态绑定的工作
  • 如果你需要使用一个通用的容器,你将需要使用POI以基类作为对象。

样品编辑:

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(); 
    } 
+0

我以前试过,但问题是它给了我一个错误:不能从'Action * const'转换为'Action' –