c++ - 从静态方法调用静态函数指针

标签 c++

我的 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/

相关文章:

c++ - boost::lexical_cast<int> 与 boost::iterator_range 的意外结果

c++ - 完美转发 setter 的正确 `enable_if` 约束是什么?

c++ - 标准功能要求

c++ - 基本类型的显式类型转换 "operators"之间有区别吗?

c++ - 为列表内部结构分配空间

c++ - 如何在多显示器设置中测试我的 Windows 应用程序?

c++ - 操作队列

c++ - 从 QGridLayout 中删除边框

c++ - C++数组传递给具有大小的函数

c++ - 在 Visual Studio 中使用 C++ 类 - 未声明的标识符错误