虚函数覆盖和隐藏 [英] Virtual functions overriding and hiding

查看:195
本文介绍了虚函数覆盖和隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

class Event{};
class CustomEvent:public Event{};

class Handler
{
  public:
      virtual void inform(Event e ){}
};

class CustomHandler : public Handler
{
  public:
    void inform(CustomEvent e){}        

};

CustomEvent cEvent;
Handler* handler = new CustomHandler;

//this calls Handler::inform(Event), not CustomHandler::(CustomEvent) , as I expected
handler->inform(cEvent); 

如果我将代码更改为:

class Handler
{
  public:
      virtual void inform(Event e ){}
      virtual void inform(CustomEvent e){}

};

class CustomHandler : public Handler
{
  public:
    void inform(CustomEvent e){}        

};

CustomEvent cEvent;
Handler* handler = new CustomHandler;

//this calls CustomHandler::(CustomEvent) 
handler->inform(cEvent);

我读到这是与函数覆盖和隐藏连接,但仍然不明白这个行为

I read that this is connected with function overriding and hiding but still doesn't understand the behavior in this code.

推荐答案

根据参数的 runtime 类型,函数重载不起作用你的参数是 CustomHandler * ),而是在他们的 static 类型(这里是 Handler * ,因为这是处理程序被声明为)。

Function overloading does not work based on the runtime type of the arguments (which for your argument here is CustomHandler*) but rather on their static type (which here is Handler*, as that's what handler is declared as).

虚函数允许你基于一个对象(您调用函数的对象)的运行时类型。基于多个对象的运行时类型调度调用称为多调度;在这种情况下,我们将讨论双调度的最常见情况。

Virtual functions allow you to make function calls based on the runtime type of one object (the one you call the function on). Dispatching calls based on the runtime type of multiple objects is called multiple dispatch; in this instace we 're talking about the most common case of double dispatch. If you want this kind of functionality you are going to have to implement double dispatch or use a library that does it for you.

The Visitor pattern is a pretty common way of doing the implementation; see also Difference betwen Visitor pattern & Double Dispatch.

最后,您可以找到一个关于Visitor的讨论,其中包括示例代码(向下滚动)此处

Finally, you can find a good discussion of Visitor which includes example code (scroll down) here.

这篇关于虚函数覆盖和隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆