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 に答える