我的 individual.hpp 文件中有以下代码:
typedef string (Individual::*getMethodName)(void);
static getMethodName currentFitnessMethodName;
static string getCurrentFitnessMethodName();
这在我的 .cpp 文件中:
string Individual::getCurrentFitnessMethodName(){
return (Individual::*currentFitnessMethodName)();
}
我在代码的其他部分使用函数指针,但始终在同一对象上下文中,因此我执行 (this->*thingyMajigger)(params),但通过该静态调用,我收到以下错误:
预期的不合格 ID
我已经尝试了上述代码的多种排列,但似乎都不起作用。谁能分享一些光吗?
干杯
最佳答案
你的 typedef 是让你陷入困境的原因。静态方法只是常规函数,恰好可以访问其类的 protected /私有(private)静态成员。
将 typedef 更改为简单的:
typedef string (*getMethodName)(void);
前一种语法适用于非静态成员方法。
作为示例,以下内容无法编译:
#include <iostream>
#include <string>
using namespace std;
class Foo {
public:
typedef string (Foo::*staticMethod)();
static staticMethod current;
static string ohaiWorld() {
return "Ohai, world!";
}
static string helloWorld() {
return "Hello, world!";
}
static string callCurrent() {
return Foo::current();
}
};
Foo::staticMethod Foo::current = &Foo::ohaiWorld;
int main() {
cout << Foo::callCurrent() << endl;
Foo::current = &Foo::helloWorld;
cout << Foo::callCurrent() << endl;
return 0;
}
但是改变 typedef
typedef string (Foo::*staticMethod)();
至
typedef string (*staticMethod)();
允许它编译 - 并按预期输出:
Ohai, world!
Hello, world!
关于c++ - 从静态方法调用静态函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467150/