我想以一种很好的方式初始化一个指针数组……就像
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} {}
关于C++在构造函数中初始化一个非静态指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32046141/