在构造函数中初始化指针的非静态数组

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

本文关键字:静态 数组 指针 构造函数 初始化      更新时间:2023-10-16

我想用一种漂亮的方式初始化一个指针数组。就像

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

then a this happened

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} {}