vendredi 21 mai 2021

How to call a member function as a callback function in C++? [duplicate]

#include <iostream>
using namespace std;
class base_A {
    void sum(int a, int b, void (*p)(int)) {
        int res = a + b;
        (*p)(res);
    }
    void print(int r) {
        cout << "res: " << r;
    }
};
int main() {
    int x,y;
    cout << "Enter two numbers to sum\n";
    cin >> x >> y;
    void (*p)(int) = base_A::print;
    void (*ptr)(int a, int b, void (*p)(int)) = base_A::sum;
    (*ptr)(x, y, *p);
    return 0;
}

Couldn't able to call the member functions. People are saying that there is a different way to access a non static member functions. I couldn't able to find a simple example program on the internet. Please anyone show me how to do it on my code.

Aucun commentaire:

Enregistrer un commentaire