C++ function pointer (class member) to non-static member function

家住魔仙堡 提交于 2019-11-26 17:31:40

The line you want is

   return (f.*f.do_something)(5);

(That compiles -- I've tried it)

"*f.do_something" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f." prefix.

 class A{
    public:
        typedef int (A::*method)();

        method p;
        A(){
            p = &A::foo;
            (this->*p)(); // <- trick 1, inner call
        }

        int foo(){
            printf("foo\n");
            return 0;
        }
    };

    void main()
    {
        A a;
        (a.*a.p)(); // <- trick 2, outer call
    }
class A {
    int var;
    int var2;
public:
    void setVar(int v);
    int getVar();
    void setVar2(int v);
    int getVar2();
    typedef int (A::*_fVar)();
    _fVar fvar;
    void setFvar(_fVar afvar) { fvar = afvar; }
    void insideCall() { (this->*fvar)(); }
};

void A::setVar(int v)
{
    var = v;
}

int A::getVar()
{
    std::cout << "A::getVar() is called. var = " << var << std::endl;
    return var;
}

void A::setVar2(int v2)
{
    var2 = v2;
}

int A::getVar2()
{
    std::cout << "A::getVar2() is called. var2 = " << var2 << std::endl;
    return var2;
}

int main()
{
    A a;
    a.setVar(3);
    a.setVar2(5);

//    a.fvar = &A::getVar;
    a.setFvar(&A::getVar);
    (a.*a.fvar)();

    a.setFvar(&A::getVar2);
    (a.*a.fvar)();

    a.setFvar(&A::getVar);
    a.insideCall();

    a.setFvar(&A::getVar2);
    a.insideCall();

    return 0;
}

I extended Nick Dandoulakis's answer. Thank you.

I added a function which set the member function pointer from outside of the class. I added another function which can be called from outside to show inner call of member function pointer.

Try (f.*do_something)(5);

#include<iostream>
using namespace std;

class A {

public:
    void hello()
    {
        cout << "hello" << endl;
    };

    int x = 0;

};


void main(void)
{

    //pointer
    A * a = new A;
    void(A::*pfun)() = &A::hello;
    int  A::*v1 = &A::x;

    (a->*pfun)();
    a->*v1 = 100;
    cout << a->*v1 << endl << endl;

    //----------------------------- 
    A  b;
    void(A::*fun)() = &A::hello;
    int  A::*v2 = &A::x;

    (b.*fun)();
    b.*v2 = 200;
    cout << b.*v2 << endl;

}

I think calling a non static member of the class could also be done using a static member function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!