如何从另一个函数执行函数?

时间:2012-07-30 17:02:45

标签: c++ qt function

我有这段代码:

#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函数中,您可以将函数作为参数放入,然后执行参数(也就是函数)。我该怎么做?

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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
}