【问题标题】:Calling a child function from a parent constant object [duplicate]从父常量对象调用子函数[重复]
【发布时间】: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();
    }

问题是它总是在主函数中调用父函数。

我在很多方面都尝试过虚函数,但我想找到一个不使用强制转换的问题的解决方案。

有可能吗?

【问题讨论】:

  • 你需要重温how polymorphism works
  • 提示。关键字覆盖是你最好的朋友:-)
  • 没有演员表是什么意思?在父函数之前添加virtual 似乎是无需重大更改的方式。
  • @aybassiony 好吧,你还需要使用指针,当你使用它们时,你会得到从派生类到基类指针的隐式转换。
  • 所以我必须制作一个指针列表,如 const std::vector listAction

标签: c++


【解决方案1】:

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

当派生类对象被分配给基类对象时,派生类对象的附加属性被切掉以形成基类对象

【讨论】:

  • 谢谢我会谷歌它;)
  • 如果想达到想要的结果,就用多态吧。
【解决方案2】:

如果您不介意演员表,您需要:

  • 将父函数设为虚拟,以便动态绑定工作
  • 如果您需要使用通用容器,则需要使用指向基类的指针作为对象。

示例编辑:

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

【讨论】:

  • 我之前尝试过,但问题是它给了我一个`错误:无法从'Action *const'转换为'Action'`
猜你喜欢
  • 1970-01-01
  • 2021-06-19
  • 2010-09-29
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多