我正在尝试使用函数指针初始化结构,但是除非使用全局函数完成,否则我很难这样做。以下代码有效:
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
该代码不再有效。换句话说,我将测试器功能更改为:
float MyClass::tester(float v){
return 2.0f*v;
}
感谢任何和所有帮助(包括链接)!我尝试用谷歌搜索这个问题,但不确定要搜索什么(我尝试过诸如“类中的 C++ 结构函数指针初始化”之类的东西,但无济于事)
这是因为当您将函数作为类的成员时,它将不再是该类型float (*)(float)
, 反而,float (MyClass::*)(float)
.
调查std::function http://en.cppreference.com/w/cpp/utility/functional/function and std::mem_fn http://en.cppreference.com/w/cpp/utility/functional/mem_fn来解决这些问题。
Example:
struct foo {
float bar(int x, int y) {}
};
// This works
std::function<float(int, int)> func = std::mem_fn(&foo::bar);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)