从静态方法调用静态函数指针
Calling static function pointer from static method
我的 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!
相关文章:
- 指向模板上下文中的成员函数或静态函数的指针
- 函数指针静态,构造函数
- 在构造函数中初始化静态函数指针
- 从静态方法调用静态函数指针
- 为什么静态指针返回函数中有一个"静态"键?
- C++ - 模板类 -> 静态函数 -> 静态函数指针的链接错误
- 静态函数到类的静态指针之间的区别是什么
- 将对象的方法指针传递给接受 [静态方法指针/全局函数] 指针的函数
- 模板类中静态函数或指针的作用域解析
- 通过C++中的非静态函数设置对C函数指针的回调
- C++,在类构造函数中传递非静态函数指针
- 指向非静态函数的函数指针
- 在静态函数中调用成员函数指针
- 通过此指针从静态函数调用类函数
- 指向可变参数模板静态函数的指针.如何
- C++使用预定义参数调用静态函数指针
- 将参数中的静态函数指针替换为实例中方法的指针
- 函数可以接受静态函数指针作为参数吗?
- 将非静态函数指针传递给另一个类
- 在不同类中使用和设置静态函数指针