C++ inheritance and member function pointers

前端 未结 8 803
忘了有多久
忘了有多久 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:05

    Here is an example of what works. You can override a method in derived class, and another method of base class that uses pointer to this overridden method indeed calls the derived class's method.

    #include 
    #include 
    
    using namespace std;
    
    class A {
    public:
        virtual void traverse(string arg) {
            find(&A::visit, arg);
        }
    
    protected:
        virtual void find(void (A::*method)(string arg),  string arg) {
            (this->*method)(arg);
        }
    
        virtual void visit(string arg) {
            cout << "A::visit, arg:" << arg << endl;
        }
    };
    
    class B : public A {
    protected:
        virtual void visit(string arg) {
            cout << "B::visit, arg:" << arg << endl;
        }
    };
    
    int main()
    {
        A a;
        B b;
        a.traverse("one");
        b.traverse("two");
        return 0;
    }
    

提交回复
热议问题