C ++ - 基类指针,方法指针,引用派生类,方法?

时间:2014-04-01 06:00:25

标签: c++ pointers

class Base
{
    virtual void Foo(){}
    virtual void Bar(){}
};

class Derived1 : public Base
{
    void Foo(){ //Do something }
    void Bar(){ //Do something }
}

class Derived2 : public Base
{
    void Foo(){ //Do something }
    void Bar(){ //Do something }
}

class OtherClass
{
public:
    Base* obj;
    void (Base::*method)();

    void Add( Base* _obj, void (Base::*_method)() )
    {
        obj = _obj;
        method = _method;
    }

    void Run()
    {
        ( obj->method )();
    }
}

int main()
{
    Derived1 d1;
    Derived2 d2;

    OtherClass other;

    other.Add( &d1, &(Derived1::Foo) );
    //other.Add( &d2, &(Derived2::Bar) ); etc, etc.

    other.Run();
}

我的问题:

假设我有一个带有方法的派生类,我可以使用它的基类型指针来引用该类的实例。假设我知道我想调用什么方法,然后我可以通过该指针调用它,并且将调用派生类的方法。

当我通过提供方法指针指定要调用的方法时,如何实现类似的多态行为?

上面的真实代码是基于将编译的,如果我转换方法指针,但它似乎没有做任何 - 在这一点上,我已经意识到我没有调用OtherClass&# 39;更新方法,这就是为什么我没有获得任何快乐。 :D所以这样做(几乎)。愚蠢的,愚蠢的大脑。

然后稍微修正一下:现在我需要将传递给OtherClass的方法指针静态转换为指向Base类方法的指针,当我将它传递给Add时。这不太理想。

如果我将&(Base :: Foo)传递给方法Add?

,我可以得到相同的行为吗?

如果我在指向派生类型实例的基类型的指针上调用该方法,那么Derived1 :: Foo会被调用吗?

我感觉它会打电话给基地会员。 :(

一些阅读: Is it safe to "upcast" a method pointer and use it with base class pointer? C++ inheritance and member function pointers Pointer to member conversion Casting a pointer to a method of a derived class to a pointer to a method of a base class

1 个答案:

答案 0 :(得分:0)

我相信你正在思考虚拟基类的成员-fn-ptr是否会在派生类中提供多态派生覆盖。如果是这样,答案是肯定的,下面的代码证明了这一点。

希望这有帮助。

#include <iostream>

class Base
{
public:
    virtual void Foo()
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
    virtual void Bar()
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};

class Derived1 : public Base
{
public:
    void Foo()
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }

    void Bar()
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};

class Derived2 : public Base
{
public:
    void Foo()
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }

    void Bar()
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};

class OtherClass
{
public:
    Base* obj;
    void (Base::*method)();

    void Add( Base* _obj, void (Base::*_method)() )
    {
        obj = _obj;
        method = _method;
    }

    void Run()
    {
        (obj->*method)();
    }
};

int main()
{
    Derived1 d1;
    Derived2 d2;

    OtherClass other;

    other.Add( &d1, &Base::Foo );
    other.Run();

    other.Add( &d2, &Base::Bar);
    other.Run();
}

<强>输出

virtual void Derived1::Foo()
virtual void Derived2::Bar()
相关问题