这实质上就是我想要做的,但不是实际的源代码。为什么这个数组不能初始化?
namespace namespace { int array [3]; } namespace::array={1,2,3}
我的gcc询问的表情,我不知道该怎么做。我必须namespace::array[1];
每个单独的元素?
这实质上就是我想要做的,但不是实际的源代码。为什么这个数组不能初始化?
namespace namespace { int array [3]; } namespace::array={1,2,3}
我的gcc询问的表情,我不知道该怎么做。我必须namespace::array[1];
每个单独的元素?
只能在定义中使用的初始化列表:
int array[3] = { 1, 2, 3 };
如果你使用:
int array[3];
,那么你需要初始化函数中的数组,使用
array[0] = 1;
array[1] = 2;
array[2] = 3;
namespace ns { int array[3] = {1, 2, 3}; }
怎么样?
虽然C99和C++的奇数混合物,GCC允许这样的:
#include <string.h>
int a[3];
int main()
{
memcpy(a, (int[3]){ 1, 2, 3}, sizeof(a));
}
!
有几种方法:
1)每个元素明确设置值:
namespace ns {
int array [3];
}
ns::array[0]=1;
ns::array[1]=2;
ns::array[2]=3;
\\ or if they should contain consequtive values:
\\ for (size_t i = 0; i < 3; ++i)
\\ ns::array[i] = i + 1;
2)如果你想在地方其声明中初始化静态数组,那么你可以将它初始化列表如下:
namespace ns {
int array[3] = {1, 2, 3};
}
3)使用typedef
:
namespace ns {
typedef int array_t[3];
}
ns::array_t array = {1, 2, 3};
3)您还可以的std :: TR1 ::阵列,它可以被用作这样的一些研究:
std::tr1::array<int, 3> arr = {1, 2, 3};
..that确实奇怪,我从来没有见过这样的事情之前! +1为唯一... – Nim 2011-04-14 22:01:24
我检查了装配,它确实有效。我怀疑它也适用于非常量表达式。 – 2011-04-14 22:03:07