开发者

Arrays split into header and source files

for some bizarre reason I always forget the exact syntax of arrays. How do I create an array in the header and initialise it in the constructor? Is it 开发者_如何学运维possible to initialise it in the header as well as defining it?


You can use the extern keyword to declare variables in the header, but defining in the header might lead to multiple definitions and linker errors (unless you use static keyword and header-guards, in which case you'd be creating separate array instances per each translation unit).

For example:

Header

extern int array[ARRAY_SIZE];
static int stArray[ARRAY_SIZE] = {initialized static array};

X.CPP

#include the header
int array[ARRAY_SIZE] = {initialize here}
... some code
int i = array[index]; //access the array initialized in X.CPP
int j = stArray[index]; //access the array initialized in X.CPP
                      //when including the header

Y.CPP

#include the header
// don't initialize
...
in some code do:
int i = array[index]; // you'll access the array initialized in X.CPP.
int j = stArray[index]; //access the array initialized in Y.CPP when
                   // including the header, not the same as in X.CPP

Edit

Re class members - they're usually defined in header files, but they're created when the class instances (objects) are created, and should be initialized in the constructor. Unless you're marking them as static, and then you have to define them in a CPP file somewhere (in a similar fashion to the extern variables).

Also, it was mentioned in the comments: global variables should not be accessed prior to main being called (i.e.: one global/static variable shouldn't be initialized based on the value of another global/static value). That might lead to a problem known as Static Initialization Fiasco.


Well, you COULD always use a pointer and do it dynamically...Just have to remember to clean it up with delete[].

In the header, just declare a pointer...

   int * x = 0;

And in the cpp, call new and do what you need with it.

   x = new int[15];
   //do stuff
   delete [] x;


I have since read up on this issue a little more and it seems it is not possible: This actually hits on one of the shortcomings of the C++ language — there is no way to initialize non-static array members in C++.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜