C++在构造函数中初始化一个非静态指针数组

Wer*_* Bn 0 c++ arrays pointers function-pointers

我想以一种很好的方式初始化一个指针数组..有点像

handler[numberOfIndexes] = {&bla, &ble, &bli, &blo , &blu};
Run Code Online (Sandbox Code Playgroud)

但它不会这样工作.显然,我得到一个错误,因为我试图在函数的单个指针中放置一个函数指针数组:

cannot convert ‘<brace-enclosed initializer list>’ to ‘void (A::*)()’ in assignment
Run Code Online (Sandbox Code Playgroud)

那么,这是您要测试的代码:

#include <iostream>
#include <list>

using namespace std;

class A
{
    private:

    void first();
    void second();
    void third ();
    // and so on

    void(A::*handlers[4])(void);


    public:

    A();
};

void A::first()
{

}

void A::second()
{

}

void A::third()
{

}

A::A()
{
    //this is ugly
    handlers[0] = &A::first; 
    handlers[1] = &A::second;
    handlers[2] = &A::third;

    //this would be nice
    handlers[4] = {&A::first,&A::second,&A::third,0};//in static this would work, because it would be like redeclaration, with the type speficier behind
}

int main()
{
    A sup;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

更新:在Qt中,这不起作用.我明白了:

syntax error: missing ';' before '}'
Run Code Online (Sandbox Code Playgroud)

如果我换到

A::A() : handlers ({&A::first, &A::second, &A::third, 0})//notice the parentheses
Run Code Online (Sandbox Code Playgroud)

然后这发生了

Syntax Error: missing ')' before '{'
Warning: The elements of the array "A :: Handlers" are by default "initialized.
Run Code Online (Sandbox Code Playgroud)

那么,Qt的问题是什么?


到此为止,你应该明白我想做什么.只需对指针数组进行一次很好的初始化.谢谢.

Que*_*tin 6

只使用实际的初始化,而不是赋值(无法将数组赋值).

A::A() : handlers {&A::first, &A::second, &A::third, 0} {}
Run Code Online (Sandbox Code Playgroud)