没办法
使用g ++编译器。

码:

#include <iostream>

using namespace std;

typedef void (* FPTR) ();

class Test
{
    void f1()
    {
        cout << "Do nothing 1" << endl;
    }

    void f2()
    {
        cout << "Do nothing 2" << endl;
    }

    static FPTR const fa[];
};

FPTR const Test::fa[] = {f1, f2};


错误:

test.cpp:22: error: argument of type ‘void (Test::)()’ does not match ‘void (* const)()’
test.cpp:22: error: argument of type ‘void (Test::)()’ does not match ‘void (* const)()’


我只想获取函数指针的常量数组,所以

fa[0] = f2;


会导致类似“修改只读成员Test :: fa”的错误

最佳答案

编译器是正确的。指针类型为void (Test::*)()。尝试一下:

typedef void (Test::*FPTR)();

FPTR const Test::fa[] = { &Test::f1, &Test::f2 };  // nicer to read!


f1f2不是函数(即自由函数),而是(非静态)成员函数。那是完全不同的动物:您可以调用一个函数,但不能仅调用成员函数。您只能在实例对象上调用成员函数,而其他任何事情都没有意义。

10-04 14:54