使得在C常量数组++ [英] making a constant array in c++

查看:151
本文介绍了使得在C常量数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何理由,$ C $个cblocks告诉我,我不能让一个数组?我只是试图做的:

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};

和它给了我

错误:一个大括号内的初始化在这里不允许使用前'{'令牌

error: a brace-enclosed initializer is not allowed here before '{' token

我已经改变了初始的其他部位,但错误总是说同样的事情。这似乎没有什么意义,因为这是第一件事情我在C ++中了解到的。

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++.

推荐答案

您说,你这样做是一个类中,作为私有变量。

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).

struct T {
   std::string str = "lol";
};

也不行。它必须是:

is not ok. It has to be:

struct T {
   std::string str;
   T() : str("lol") {}
};

但是,要雪上加霜,pre-C ++ 0x中,你不能初始化在构造函数初始化值阵列

struct T {
   const unsigned int array[10];
   T() : array({0,1,2,3,4,5,6,7,8,9}) {} // not possible :(
};

和,因为你的数组的元素是常量,你不能依靠转让或者:

And, because your array's elements are const, you can't rely on assignment either:

struct T {
   const unsigned int array[10];
   T() {
       for (int i = 0; i < 10; i++)
          array[i] = i; // not possible :(
   }
};

然而,其他一些参与者已相当正确地指出的那样,似乎没有点在数组的副本 T的每个实例如果您不能修改它的元素。相反,你可以使用静态成员。

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 a static member.

因此​​,下面将最终解决什么&MDASH你的问题。或许&MDASH;最好的方式:

So, the following will ultimately solve your problem in what's — probably — the best way:

struct T {
   static const unsigned int array[10];
};

const unsigned int T::array[10] = {0,1,2,3,4,5,6,7,8,9};

希望这有助于。

这篇关于使得在C常量数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆