从静态方法调用静态函数指针

Calling static function pointer from static method

本文关键字:指针 静态函数 调用 静态方法      更新时间:2023-10-16

我的 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 是搞砸你的原因。静态方法只是常规函数,恰好可以访问其类的受保护/私有静态成员。

将 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 string (Foo::*staticMethod)();

typedef string (*staticMethod)();

允许它编译 - 并按预期输出:

Ohai, world!
Hello, world!