I now I can do this in global scope and everything works fine:
const char* Foo::bars[3] = {"a", "b", "c"};
But I want to do this because this is much more clearer and self documenting (especially if you use Enums as the index):
const char* Foo::bars[3];
bars[0] = "a";
bars[1] = "b";
bars[2] = "c";
Is it anyway possible?
I know I can do this inside a function (for example, the class's constructor) but what if the constructor is not called in the start of the program and I want to use the static array? That leads to problems.
How about this?
const char* Foo::bars[3] = {
/* Index Value */
/* 0 */ "a",
/* 1 */ "b",
/* 2 */ "c"
};
I often use this "technique" to make the initialization of arrays of structs look like a self-documenting spreadsheet.
In C++ there is no equivalent of the static
Java block.
If you really want to initialize the array automatically, you can create a simple class to do the job:
// in .cpp
class FooInitializer {
public:
FooInitializer() {
Foo:bars[0] = "a";
Foo:bars[1] = "b";
Foo:bars[2] = "c";
}
};
static FooInitializer fooInitializer;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With