看完How to initialize an array in C ,特别是:
Don't overlook the obvious solution, though:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
我试过这样的:
#include <iostream>
class Something {
private:
int myArray[10];
public:
Something() {
myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
}
int ShowThingy(int what) {
return myArray[what];
}
~Something() {}
};
int main () {
Something Thing;
std::cerr << Thing.ShowThingy(3);
}
然后我得到:
..\src\Something.cpp: In constructor 'Something::Something()':
..\src\Something.cpp:10:48: error: cannot convert '<brace-enclosed initializer list>' to 'int' in assignment
在这种情况下显而易见的不是那么明显。我真的希望我的阵列的启动也更加动态。
我累了:
private:
int * myArray;
public:
Something() {
myArray = new int [10];
myArray = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
}
这对我来说看起来很时髦,对编译器来说也是如此:
..\src\Something.cpp: In constructor 'Something::Something()':
..\src\Something.cpp:11:44: error: cannot convert '<brace-enclosed initializer list>' to 'int*' in assignment
这也不起作用:
private:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
与:
..\src\Something.cpp:6:20: error: a brace-enclosed initializer is not allowed here before '{' token
..\src\Something.cpp:6:51: sorry, unimplemented: non-static data member initializers
..\src\Something.cpp:6:51: error: 'constexpr' needed for in-class initialization of static data member 'myArray' of non-integral type
我一直做得很好,学习了哪些是行不通的,但学习哪些是行之有效的却不是很好。
那么,如何在类中为数组使用初始化列表 {value, value, value}?
一段时间以来,我一直在努力弄清楚如何做到这一点,但我非常困惑,我需要为我的应用制作许多此类列表。
最佳答案
需要在构造函数初始化列表中初始化数组
#include <iostream>
class Something {
private:
int myArray[10];
public:
Something()
: myArray { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }
{
}
int ShowThingy(int what) {
return myArray[what];
}
~Something() {}
};
int main () {
Something Thing;
std::cerr << Thing.ShowThingy(3);
}
..\src\Something.cpp:6:51: sorry, unimplemented: non-static data member initializers
C++11 还添加了对非静态成员变量的内联初始化的支持,但如上述错误消息所述,您的编译器尚未实现此功能。
关于c++ - 如何在 C++ 对象中初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10694689/