C ++:初始化结构和设置函数指针 [英] C++: Initializing Struct and Setting Function Pointer

查看:158
本文介绍了C ++:初始化结构和设置函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用函数指针初始化一个结构体,但是我有麻烦这样做,除非它是一个全局函数。以下代码工作原理:

I am trying to initialize a struct with a function pointer, however I am having trouble doing so unless it is done with a global function. The following code works:

float tester(float v){
    return 2.0f*v;
}

struct MyClass::Example{
    typedef float(*MyFunc)(float);

    MyFunc NameOfFunc;

    float DoSomething(float a){
        return NameOfFunc(a);
    }
};

struct Example e;
e.MyFunc = tester;

我的问题是每当我尝试用 tester 函数作为 MyClass 中的函数,代码不再有效。换句话说,我将测试器功能更改为:

My problem is whenever I try to do this with the tester function as a function in MyClass the code no longer works. In other words, I change the tester function to:

float MyClass::tester(float v){
    return 2.0f*v;
} 

任何和所有帮助,包括链接!我已经尝试谷歌搜索的问题,但不确定搜索什么(我已经尝试过类似类中的C ++结构函数指针初始化无效)

Any and all help is appreciated (including links)! I have tried googling around for the problem but am unsure what to search (I've tried things such as "C++ struct function pointer initialization in class" to no avail)

推荐答案

这是因为当你把函数作为类的成员,它将不再是类型 float(*)(float),而是 float(MyClass :: *)(float)

This is because when you put the function as a member of the class, it will no longer be of the type float (*)(float), but rather, float (MyClass::*)(float).

href =http://en.cppreference.com/w/cpp/utility/functional/function =nofollow> std :: function std :: mem_fn 来解决这些问题。

Look into std::function and std::mem_fn to solve these problems.

示例:

struct foo {
    float bar(int x, int y) {}
};

// This works
std::function<float(int, int)> func = std::mem_fn(&foo::bar);

这篇关于C ++:初始化结构和设置函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆