在构造函数中初始化指针的非静态数组
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
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} {}
相关文章:
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 静态数组的自由动态数组
- 如何在C++中删除静态数组?
- 为什么 &a 和 c++ 中的静态数组相同?
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 将在堆栈上声明的元素添加到静态数组
- const_cast静态数组以添加恒常性
- 动态分配的数组和静态数组之间的区别
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- 我可以使用 constexpr 函数声明一个静态数组吗?
- 使用 lambda 初始化静态数组
- 为什么从函数返回数组时需要将数组声明为静态数组.(C++)
- 根据模板值确定的静态数组大小
- 如何使用 PHP-CPP 在 PHP 类中添加静态数组
- 包含不同大小静态数组的类的多个实例
- 从我的对象返回静态数组
- 如何避免在类中显式指定静态数组的大小
- 编译类型的时静态数组
- 来自函数参数的 C++ 静态数组声明