简体   繁体   中英

Passing member function as parameter to another function in c++

I have the following problem. I have a base abstract class with a pure virtual method, and I want to pass it as an argument to another member function(so not a normal function). Yet I have an error when trying to call the method with specified function. Code speaks better than words so bellow I have posted the code that generates the problem

class BaseClass
{
public:
    BaseClass();
    int add(int, int);
    virtual void op(void (*f)(int, int), string s, int a, int b) = 0;
    ~BaseClass();
};
#include "BaseClass.h"
class ClasaDerviata:public BaseClass
{
public:

    ClasaDerviata();
    void testNumere(int a, int b);
    void op(void(*f)(int, int), string s, int a, int b);
    ~ClasaDerviata();
};
#include "BaseClass.h"

BaseClass::BaseClass()
{
}
int BaseClass::add(int a, int b)
{
    return a + b;
}

BaseClass::~BaseClass()
{
}

#include "ClasaDerviata.h"
#include <iostream>

using namespace std;


ClasaDerviata::ClasaDerviata()
{
}
void ClasaDerviata::testNumere(int a, int b)
{
    cout << a + b << "\n";
    cout << " suma " << add(a,b) << "\n";
}
void ClasaDerviata :: op (void (*f)(int, int), string s, int a, int b)
{
    f(a, b);
   cout << s << "\n";
}
ClasaDerviata::~ClasaDerviata()
{
}
#include "ClasaDerviata.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    ClasaDerviata *a;
    a = new ClasaDerviata();
    int x, y;
    cin >> x >> y;
    a->op(&ClasaDerviata::testNumere, "test metoda", x, y);

    system("pause");

    return 0;
}

Thank you for your time!

void ClasaDerviata::testNumere(int a, int b); is not of type void (*)(int, int) but void (ClasaDerviata::*)(int, int)

You may add static to testNumere and add to fix your problem or change signature of your function (and change internal code too).

Remember when you make a call to a member function a hidden parameter 'this' is passed. So your ClasaDerviata::testNumere(int a, int b); function actually takes three parameters. I would suggest to read Joseph Garvin comment in How can I pass a class member function as a callback?

he has explained it very well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM