Call any function of another class of the same type

Asked

Viewed 1,360 times

0

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

#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.

  • The problem is that the method MyP of MyPrint is an instance method, so you need the reference to the object. If you make it static you will see that it works.

  • I found a solution that can call non-static functions within the friend class. I put it hereCall Ticker library from Another Class1

1 answer

2


The problem is that every instance method requires an object. If it were specified as static function. 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 object method 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;

}
  • Here returns: 'void Myclass::Myc<Myprint>(T ,void (__thiscall Myprint:: )(int)': cannot convert a 2 argument from 'void (__cdecl )(int)' in 'void (__thiscall Myprint:: )(int)'

  • Copiei e colei e fiz algumas pequenas alterações:&#xA;Retirei os ´__PRETTY_FUNCTION__´&#xA;Alterei o ´StaticMyP´ para só ´MyP´&#xA;No main ao invez de ´P.MyC(&A, &MyPrint::MyP);´ coloquei ´P.MyC<MyPrint>(&A, &MyPrint::MyP);&#xA;&#xA;O resto está idêntico&#xA;I made these changes because there were several errors

  • I will try to compile in Windows with template to see what the problem is, but meanwhile I will update the example to use fixed type.

  • Worked, put the agr template and tbm gave

Browser other questions tagged

You are not signed in. Login or sign up in order to post.