C ++双重派遣问题 [英] C++ Double Dispatch problems

查看:137
本文介绍了C ++双重派遣问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前问过的问题的第2部分:

This is part 2 to a problem I previously asked: Is it possible to have polymorphic member overloading in C++?

使用Wiki示例,我创建了此示例. http://en.wikipedia.org/wiki/Double_dispatch

Using the Wiki example I created this example. http://en.wikipedia.org/wiki/Double_dispatch

我的问题是,编译后的代码从不查找vtable,并且始终使用基类而不是继承的类.这是我的代码:

My problem is that the compiled code never looks up the vtable, and always uses the base instead of the inherited class. Here is my code:

#include <iostream>

class xEntity;
class xVehicle;

class xMapObject
{
  public:
    virtual void Bump(xMapObject&) { std::cout << "MapObject Bump MapObject\n"; };
    virtual void Bump(xEntity&) { std::cout << "MapObject Bump Entity\n"; };
    virtual void Bump(xVehicle&) { std::cout << "MapObject Bump Vehicle\n"; };
};

class xEntity : public xMapObject
{
  public:
    virtual void Bump(xMapObject&) { std::cout << "Entity Bump MapObject\n"; };
    virtual void Bump(xEntity&) { std::cout << "Entity Bump Entity\n"; };
    virtual void Bump(xVehicle&) { std::cout << "Entity Bump Vehicle\n"; };
};

class xVehicle : public xEntity
{
  public:
    virtual void Bump(xMapObject&) { std::cout << "Vehicle Bump MapObject\n"; };
    virtual void Bump(xEntity&) { std::cout << "Vehicle Bump Entity\n"; };
    virtual void Bump(xVehicle&) { std::cout << "Vehicle Bump Vehicle\n"; };
};

int main(int argv, char **argc)
{
    xEntity Entity;
    xVehicle Vechile;

    xMapObject &EntityRef = Entity;
    xMapObject &VehicleRef = Vechile;

    VehicleRef.Bump(EntityRef);

    return 0;
}

但是,输出始终为:

Vehicle Bump MapObject

对于这个谜题的任何帮助,我们将不胜感激.

Any help on this mystery is greatly appreciated.

推荐答案

您只执行了一次调度,而不是两次调度.这个想法是,在xVehicle中,取一个xMapObject&,您将调用ref.bump(*this);,它是 的双重分派.

You only did single dispatch, not double dispatch. The idea is that in xVehicle, taking an xMapObject&, you would call ref.bump(*this); which is double dispatch.

这篇关于C ++双重派遣问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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