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

C++ Initialize a non-static array of pointers in constructor

我想以一种很好的方式初始化一个指针数组。类似于

handler[numberOfIndexes] = {&bla, &ble, &bli, &blo , &blu};

但是这样不行。很明显,我收到一个错误,因为我试图将一个指向函数的指针数组放在一个指向函数的指针中:

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

所以,这是供您测试的代码:

#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;
}

更新: 在 Qt 中这是行不通的。 我得到:

syntax error: missing ';' before '}'

如果我改成

A::A() : handlers ({&A::first, &A::second, &A::third, 0})//notice the parentheses

然后发生这种情况

Syntax Error: missing ')' before '{'
Warning: The elements of the array "A :: Handlers" are by default "initialized.

那么,Qt 有什么问题?


到这里,你应该明白我想做什么了。只需对指针数组进行良好的初始化即可。 谢谢。

只使用实际的初始化,而不是赋值(不能赋值给数组)。

A::A() : handlers {&A::first, &A::second, &A::third, 0} {}