This is related to some other questions, such as: this, and some of my other questions.
In this question, and others, we see we can declare and initialise string arrays in one nice step, for example:
const char* const list[] = {"zip", "zam", "bam"}; //from other question
This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.
What I want to do is to have an array like this as as member of a class I am using, something like this:
class DataProvider : public SomethingElse { const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"}; public: DataProvider(); ~DataProvider(); char* GetData() { int index = GetCurrentIndex(); //work out the index based on some other data return mStringData[index]; //error checking and what have you omitted } };
But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?
The header file -- the whole thing: array.h This header file is similar in format to the Rational class examples. The preprocessor statements and the using statement at the beginning of the . h file are similar (except a different identifier, ARRAY_H, to match the filename is used):
int array[4] = {1,2,3,4}; will work, but putting objects in headers is generally a bad idea because it is easy to accidentally define the object multiple times just by including the header more than once. Inclusion guards are only a partial fix for that problem.
The usual way of declaring an array is to simply line up the type name, followed by a variable name, followed by a size in brackets, as in this line of code: int Numbers[10]; This code declares an array of 10 integers. The first element gets index 0, and the final element gets index 9.
A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (such as int, float ...), name is a valid identifier and the elements field (which is always enclosed in square brackets [] ), specifies the size of the array.
Use the keyword static and external initialization to make the array a static member of the class:
In the header file:
class DataProvider : public SomethingElse { static const char* const mStringData[]; public: DataProvider(); ~DataProvider(); const char* const GetData() { int index = GetCurrentIndex(); //work out the index based on some other data return mStringData[index]; //error checking and what have you omitted } };
In the .cpp file:
const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
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