将Void作为指针传入类,然后执行其内容

Passing Void into a class as a pointer then executing its contents

本文关键字:然后 执行 Void 指针      更新时间:2023-10-16

如何传递一个函数作为参数,然后执行它。我想做这样的事情:

class Foo{
private:
    void (*external);
public:
    Foo(void (*function)()){ *external = *function; }
    ~Foo(){ }
    bool Execute(){ 
        *external(); // Somehow execute 'external' which does the same thing with 'function' 
        return true
    }
};
void pFnc(){
printf("test");
}

int main(){
 Foo foo = Foo(&pFnc);
 foo.Execute();
 return 0;
}

你差一点。

class Foo
{
public:
    typedef void(*FN)(void);
    Foo(FN fn) : fn_(fn) {};
    bool Execute()
    {
        fn_();
        return true;
    }
    FN fn_;
};
void pFunc(){
    printf("test");
}
int main()
{
    Foo foo(&pFunc);
    foo.Execute();
}

尝试:

    void (*external)();

你最初的声明是指向void的指针,而不是指向返回void的函数的指针。

设置为

external = function;

和execute with

external();

同时,external必须声明为函数指针void (*external)()。否则,必须在函数指针和空指针之间进行强制转换。

相关文章: