2012-07-30 99 views
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功能,你可以把你的函数作为参数,然后它会执行参数(又名功能)。我将如何做到这一点?

回答

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 
} 
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); 
} 
相关问题