Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

making a constant array in 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++.

question from:https://stackoverflow.com/questions/6036453/making-a-constant-array-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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") {}
};

But, to add insult to injury, pre-C++0x you cannot initialise arrays in the ctor-initializer!:

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

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.

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

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...