c++ - 将 Void 作为指针传递给类,然后执行其内容

标签 c++ function pointers arguments void

如何将函数作为参数传递然后执行它。我正在尝试做这样的事情:

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();
}

关于c++ - 将 Void 作为指针传递给类,然后执行其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421886/

相关文章:

c++ - 将指向结构的指针转换为指向该结构的唯一成员的指针

c++ - VS 2013 errorC3861 PeekMessage等和errorC2065 WNDCLASSEX

javascript - 在 Javascript 中将名称定义添加到 "Function"

C++ Unicode 问题

c - C中的函数指针转换

function - 你如何在swift中访问函数外部的变量

pointers - 在 Go 中,结构指针不是引用类型吗?

c - 返回全局字符串变量的地址

c++ - Makefile 在不同的步骤中处理不同的文件

c++ - 如何为动态类型成员调用boost register_type函数