[英]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} {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.