2010-12-02 47 views
0

他们是什么,他们之间有什么不同?多派遣和多方法

来源很多,像Wikipedia,声称他们是同样的事情,但也有人明确表示,相反,像SBIthis question

第一:“访问者模式是一种方法来模拟双调度在C++中“。这是,呃,不完全正确。实际上,双派遣是多派遣的一种形式,这是一种在C++中模拟(缺少)多派的方法。

回答

5

它们是相同的。

当您在C++中调用虚拟方法时,实际要运行的方法是基于它们方法被调用的对象的运行时类型。这被称为“单个分派”,因为它取决于单个参数的类型(在这种情况下,隐含的'this'参数)。所以,举例如下:

class Base { 
    public: 
    virtual int Foo() { return 3; } 
} 

class Derived : public Base { 
    public: 
    virtual int Foo() { return 123; } 
} 

int main(int argc, char *argv[]) { 
    Base* base = new Derived; 
    cout << "The result is " << base->Foo(); 
    delete base; 
    return 0; 
} 

运行时,上面的程序打印123,而不是3.到目前为止好。

多次调度是语言或运行时在“this”指针的类型和方法参数的类型上分派的能力。考虑(与C++语法坚持的时刻):

class Derived; 

class Base { 
    public: 
    virtual int Foo(Base *b) { cout << "Called Base::Foo with a Base*"; } 
    virtual int Foo(Derived *d) { cout << "Called Base::Foo with a Derived*"; } 
} 

class Derived : public Base { 
    public: 
    virtual int Foo(Base *b) { cout << "Called Derived::Foo with a Base*"; } 
    virtual int Foo(Derived *d) { cout << "Called Derived::Foo with a Derived*"; } 
} 

int main(int argc, char *argv[]) { 
    Base* base = new Derived; 
    Base* arg = new Derived; 

    base->Foo(arg); 

    delete base; 
    delete arg; 
    return 0; 
} 

如果C++有多重调度,程序将打印“称为派生::美孚与Dervied *”。 (可惜的是,C++没有多次调度,所以程序打印出“被调用的Derived :: Foo with a Base *”。)

Double-dispatch是多派遣的一个特例,通常更容易模拟,但作为一种语言功能并不十分常见。大多数语言都是单发或多发。