c++ - MFC C++ 指向函数新手的指针

标签 c++ pointers mfc

我有很多项目的解决方案。
我想在接收数组和函数指针的公共(public)项目中创建一个类。
此类是该解决方案中其他项目的成员。每个项目类都可以将其作为成员持有。

在公共(public)类的构造函数中,如何传递函数的指针?我如何在公共(public)类中设置一个成员来保存我稍后要调用的函数的位置?

我的目标是我可以使用指针调用函数 - 而我在公共(public)项目中找到的类的代码中..

谢谢

最佳答案

On the constructor of the class inside common, How do i pass the pointer of the function ? how do i set a member inside the common class that holds the location of the function i would like to invoke later on ?

typedef void(*FUNCPTR)(int);

这定义了我的函数指针类型,但它也将函数限制为下面的签名(返回 void 并采用 1 个 int 参数)你需要为你的函数签名定义它。

void myFunction( int someParam )
{
    //DoSomething with someParam
}


class Foo
{
private:
    FUNCPTR mFunction; //Holds pointer

public:
    Foo( FUNCPTR function) : mFunction(function) {} //Initialise instance

    void callFunc() {mFunction(1);} //call function
};

int main(unsigned int argc, const char** argv)
{
    Foo myFoo(myFunction);

    myFoo.callFunc();
}

在 C++ 中,你可能会更好,但是考虑使用函数对象,你可以在其中创建一个对象并定义一个 operator(),它采用正确的参数和返回类型,但会允许你所有的灵 active 对象和多态性....

参见 C++ Functors - and their uses一些讨论和细节

关于c++ - MFC C++ 指向函数新手的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13566266/

相关文章:

c++ - 将时间戳写入文件

PHP 指针与引用

c++ - 嵌入式(半导体)项目中的 MFC、C++

c++ - 以编程方式更改系统视觉效果

c++ - 在 MFC 上单击按钮时显示文本

c++ - 将 truthTable 结果转换为 bool 语句

c++ - 当许多单元格同时可见时,QTableView 滚动缓慢

c - 由于 C 中的这些指针和数组,程序崩溃

c - 指针和字符数组

c++ - C++存储和更新排序项目的有效方法