【问题标题】:Calling overloaded method with derived class使用派生类调用重载方法
【发布时间】:2014-10-31 03:26:58
【问题描述】:

有些事情我无法用派生类做。 基本上,我有一个带有交互方法的基类,该方法将另一个基类对象作为参数。然后我有一个派生类,我希望它重载交互方法 - 派生类对象应该以自己的风格进行交互。到目前为止一切顺利,使用虚拟方法我得到了我想要的行为。但是,我还想重载交互方法,以便它可以将派生类对象作为参数。

现在,我有一个带有基类参数的对象。当我使用派生类作为参数创建这样一个对象并使其与另一个使用派生类作为参数创建的对象交互时,它确实调用了派生类的交互方法(如预期的那样)但考虑使用基类的方法范围。有没有办法让它使用其他方法?

代码如下,我希望这更清楚

#include <iostream>

class BaseClass{
public:
    BaseClass();
    virtual ~Baseclass();

    virtual void interact(BaseClass* interaction_target){std::cout << "base class interaction" << std::endl;}
};

class DerivedClass : BaseClass{
public:
    DerivedClass();
    virtual ~DerivedClass();

    virtual void interact(BaseClass* interaction_target){std::cout << "derived class interaction" << std::endl;}
    virtual void interact(DerivedClass* interaction_target){std::cout << "interaction eased by the fact that two DerivedClass object are interacting" << std::endl;}
};

class MyObject{
protected:
    BaseClass* interactor;
public:
    MyObject(BaseClass* param) : interactor(param){}
    virtual ~MyObject();

    void ObjectInteraction(MyObject interaction_target){interactor->interact(interaction_target.interactor);}
};

int main(){

MyObject first_obj(new DerivedClass());
MyObject sec_obj(new DerivedClass());

first_obj.ObjectInteraction(sec_obj); // prints derived class interactions, whereas I would like
// it to use the second method ie. interact(DerivedClass*)
return 0;
}

有没有办法做到这一点?

【问题讨论】:

    标签: c++ inheritance virtual


    【解决方案1】:

    是的。您在这里尝试执行的操作称为“双重调度”,或者更一般地说,“multiple dispatch”。 C++ 不直接支持它(某些语言支持),但您可以使用Visitor Pattern 自己实现它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多