在 c++ 中制作常量数组
代码块告诉我无法创建数组有什么原因吗?我只是想做:
const unsigned int ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};
它给了我
错误:在“{”标记之前不允许使用大括号括起来的初始值设定项
我已经更改了初始化程序的其他部分,但错误总是说同样的事情。这似乎没有意义,因为这是我在 C++ 中学到的第一个东西。
Is there any reason why codeblocks is telling me that I can't make an array? I'm simply trying to do:
const unsigned int ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};
and it's giving me
error: a brace-enclosed initializer is not allowed here before '{' token
I have changed other parts of the initializer, but the error is always saying the same thing. This doesn't seem to make sense, since this is one of the first things I learned in c++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您说您在类中作为私有变量执行了此操作。
回想一下(目前),成员变量可能不会在声明它们的同一位置进行初始化(有一些例外)。
不行。它必须是:
但是,雪上加霜的是,在 C++0x 之前,您无法在构造函数初始化器中初始化数组!:
而且,因为数组的元素是 const code>,你也不能依赖赋值:
然而,正如其他一些贡献者非常正确地指出的那样,如果可以的话,为每个
T
实例拥有一个数组副本似乎没有什么意义不要修改它的元素。相反,您可以使用static
成员。因此,以下内容将最终以可能是最好的方式解决您的问题:
希望这会有所帮助。
You say that you did this within a class, as a private variable.
Recall that (at the moment), member variables may not be initialised in the same place where you declare them (with a few exceptions).
is not ok. It has to be:
But, to add insult to injury, pre-C++0x you cannot initialise arrays in the
ctor-initializer
!:And, because your array's elements are
const
, you can't rely on assignment either:However, as some other contributors have quite rightly pointed out, there seems little point in having a copy of the array for each instance of
T
if you can't modify its elements. Instead, you could use astatic
member.So, the following will ultimately solve your problem in what's — probably — the best way:
Hope this helps.
由于这是类中的私有成员变量(根据注释),这在C++03中确实是不允许的。
许多现代编译器部分支持的 C++0x 允许编译以下内容:
但是,非静态 const 成员只有在类的不同实例中包含不同值时才有意义。如果每个实例都包含相同的
{0,1,2,3,4,5,6,7,8,9}
,那么您应该将其设为static
,这也使得在 C++98 中执行此操作成为可能:Since this is a private member variable in a class (according to the comment), this is indeed not allowed in C++03.
C++0x, partially supported by many modern compilers, allows the following to compile:
However, non-static const members only make sense if they contain different values in different instances of the class. If every instance is to contain the same
{0,1,2,3,4,5,6,7,8,9}
, then you should make itstatic
, which also makes it possible to do this in C++98: