【发布时间】:2012-05-28 12:15:22
【问题描述】:
看完How to initialize an array in C,特别是:
不过,不要忽视显而易见的解决方案:
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} 用于类中的数组?
一段时间以来,我一直在试图弄清楚如何做到这一点,但我非常困惑,我需要为我的应用制作许多此类列表。
【问题讨论】:
-
C++ 中原始数组的一个愚蠢之处在于它们不能直接赋值。 (即,以下是不允许的。
int a[10], b[10]; a = b;) -
由于本文中提到了 C++11,我将指出 std::array:
std::array<int, 10> a = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; std::array<int, 10> b = a; std::array<int, 10> c; c.fill(5);
标签: c++ arrays class initialization