C++ inheritance and member function pointers

前端 未结 8 810
忘了有多久
忘了有多久 2020-12-03 00:58

In C++, can member function pointers be used to point to derived (or even base) class members?

EDIT: Perhaps an example will help. Suppose we have a hierarchy of t

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 01:17

    I'm not 100% sure what you are asking, but here is an example that works with virtual functions:

    #include 
    using namespace std;
    
    class A { 
    public:
        virtual void foo() { cout << "A::foo\n"; }
    };
    class B : public A {
    public:
        virtual void foo() { cout << "B::foo\n"; }
    };
    
    int main()
    {
        void (A::*bar)() = &A::foo;
        (A().*bar)();
        (B().*bar)();
        return 0;
    }
    

提交回复
热议问题