2

我有这个代码:

#ifndef FUNCSTARTER_H
#define FUNCSTARTER_H

#endif // FUNCSTARTER_H

#include <QObject>

class FunctionStarter : public QObject
{
    Q_OBJECT
public:
    FunctionStarter() {}
    virtual ~FunctionStarter() {}

public slots:
    void FuncStart(start) {
        Start the function
    }
};

在 FuncStart 函数中,您可以将函数作为参数放入,然后它会执行该参数(也称为函数)。我该怎么做?

4

2 回答 2

3

要么你传递一个函数指针,要么你定义一个仿函数类。仿函数类是重载 operator() 的类。这样,类实例就可以作为函数调用。

#include <iostream>

using namespace std;

class Functor {
public:
    void operator()(void) {
        cout << "functor called" << endl;
    }   
};


class Executor {
    public:
    void execute(Functor functor) {
        functor();
    };  
};


int main() {
    Functor f;
    Executor e;

    e.execute(f);
}
于 2012-07-30T17:06:06.280 回答
2

您将函数指针作为参数传递。这称为回调

typedef void(*FunPtr)();  //provide a friendly name for the type

class FunctionStarter : public QObject
{
public:
    void FuncStart(FunPtr) { //takes a function pointer as parameter
        FunPtr();  //invoke the function
    }
};

void foo();

int main()
{
    FunctionStarter fs;
    fs.FuncStart(&foo); //pass the pointer to the function as parameter
                        //in C++, the & is optional, put here for clarity
}
于 2012-07-30T17:04:59.523 回答