使用派生类重载函数

时间:2013-05-31 12:02:50

标签: c++ polymorphism overloading

我想做的是这样的事情:

void SomeFunction(Base *){//do something}
void SomeFunction(Derived *){//do something else}

这在C ++中是否可行?到目前为止,我的尝试只是调用函数的基本版本。 这是一个清晰的例子。

示例:

#include <iostream>
#include <vector>

class Base
{
    public:
        Base () {std::cout << "Base Constructor for " << this << std::endl;}
        void virtual PrintSomething ()
        {
            std::cout << "I am Base!" << std::endl;
        };
};

class Derived : public Base
{
    public:
        Derived () : Base () {std::cout << "Derived Construtor for " << this << std::endl;}
        void virtual PrintSomething ()
        {
            std::cout << "I am Derived!" << std::endl;
        };
};

void DoAmazingStuff ( Base * ) {std::cout << "Amazing!" << std::endl;}
void DoAmazingStuff ( Derived * ) {std::cout << "DERP!" << std::endl;}

int main ()
{
    std::vector<Base *> some_vector;

    Base *x = new Base ();
    Derived *y = new Derived ();

    some_vector.push_back ( x );
    some_vector.push_back ( y );

// This is the part that isn't functioning as expected.
/******************************************/
    DoAmazingStuff ( some_vector[0] );
    DoAmazingStuff ( some_vector[1] );
/******************************************/

    std::cin.get ();
    std::cin.get ();
    delete some_vector[0];
    delete some_vector[1];
}

永远不会调用以下行:

void DoAmazingStuff ( Derived * ) {std::cout << "DERP!" << std::endl;}

1 个答案:

答案 0 :(得分:7)

当然有可能;但只有在指针的静态类型为Derived时才会调用Derived*版本。例如:

Base * b = new Base;        // static and dynamic types are Base
Derived * d = new Derived;  // static and dynamic types are Derived
Base * bd = new Derived;    // static type Base, dynamic type Derived

SomeFunction(b);   // Base overload
SomeFunction(d);   // Derived overload
SomeFunction(bd);  // Base overload (from static type)

动态调度(基于动态类型选择函数)只会在调用虚拟成员函数时发生,而不是重载非成员函数:

struct Base {
    virtual void SomeFunction() {/*do something*/}
};
struct Derived : Base {
    virtual void SomeFunction() {/*do something else*/}
};

b->SomeFunction();  // Base version
d->SomeFunction();  // Derived override
bd->SomeFunction(); // Derived override (from dynamic type)

你可以在成员函数的帮助下实现非成员函数的动态调度:

void SomeFunction(Base * b) {b->SomeFunction();}

如评论中所述,此技术可以扩展为实现多个调度,根据多个函数参数的动态类型选择函数。但这超出了问题的范围。