Call any function of another class of the same type

0

I need to pass as parameter to a member function another member function (but from another class). I can do this for functions of the same class, but of another I still can not

#include <iostream>

using namespace std;


void MyP(int a) {
    cout << a << endl;
}

class MyPrint {
public:
    void MyP(int a) {
        cout << a << endl;
    }


};

class MyClass {
public:

    void MyC(void (*Op)(int)) {
        Op(4);
    }

};

int main() {
    MyPrint A;
    MyClass P;

    P.MyC(MyP); // Funciona -> Pega a função normal (sem a classe) 
    P.MyC(A.MyP); // Não Funciona -> Pega a função membro (da classe)

    getchar();
    return 0;

}

Thanks.

    
asked by anonymous 16.09.2017 / 14:42

1 answer

2

The problem is that every instance method requires an object. If it were specified as static would work. Example:

class MyPrint {
public:
    static void StaticMyP(int a) {
        cout << a << endl;
    }
};

int main() {
    MyClass P;

    P.MyC(&MyPrint::StaticMyP); // Funciona -> Pega o método estático (sem a classe)

    return 0;
}

But if you really want to call the method of object A it is necessary to pass a pointer (or reference) to the object in question. Example:

void MyP(int a) {
    cout << a << endl;
}

class MyPrint {
public:
    void MyP(int a) {
        cout << a << endl;
    }
};

class MyClass {
public:
    void MyC(void (*Op)(int)) {
        Op(4);
    }

    void MyC(MyPrint *obj, void (MyPrint::*Op)(int)) {
        (obj->*Op)(4);
    }
};

int main() {
    MyPrint A;
    MyClass P;

    P.MyC(MyP); // Funciona -> Pega a função normal (sem a classe) 
    P.MyC(&A, &MyPrint::MyP); // Funciona -> Pega a função membro (da classe)

    return 0;

}
    
16.09.2017 / 17:42