How to declare and initialize an array of strings within a class?
Solution 1
First: I would recommend not putting string literals into your class to represent suits, it will be a lot easier to make your logic if you use something simple, like an enum or a char.
That aside, the reason why a pointer is being used here rather than using a class such as std::string is because you are storing very simple and exact data (only four possibilities, and you don't need to search it, or split it, etc.) and as such all the extra functionality that std::string includes is unneeded.
A syntax to implement this could be:
static const char* const suits[4];
the const char*
is the type of the array (it is an array of const char pointers, which are C-style strings) and the const suits [4]
makes it an array of four of them called suits
that cannot be changed (is const).
Once the static member is declared in the class, it must be initialized elsewhere and outside the class. For example, in your .h file you would write:
class deck{
public:
static const char* const suits[4];
}
const char* const deck::suits[4]={"hearts","spades","diamonds","clubs"};
It's just how the language syntax works with static members.
Solution 2
First method with C style strings:
struct Foo {
static char const *arr[];
};
char const *Foo::arr[] = {"ace_hearts", "2_hearts", "3_hearts"};
Second method with std::string
:
struct Foo {
static std::string const arr[];
};
std::string const Foo::arr[] = {"ace_hearts", "2_hearts", "3_hearts"};
Third method with std::string
and std::array
and initializer list:
struct Foo {
static std::array<std::string, 3> const arr;
};
std::array<std::string, 3> const Foo::arr {"ace_hearts", "2_hearts", "3_hearts"};
Related videos on Youtube
Ian004
Updated on October 27, 2022Comments
-
Ian004 over 1 year
I am trying to declare an array of strings representing suits in a deck of cards in my header file and initialize it in my implementation file. I have tried
initializer_list
as well as tried to initialize it within my constructor, but nothing worked. I finally came across this link Initializing a static const array of const strings in C++, but I don't understand why this works and the previous methods do not.Why is
char
used herestatic const char * const days[]
instead of
string
? Why is a pointer being used?I am confused why I simply cannot declare and initialize the array in my header file as well.
-
Daniel Kamil Kozar over 9 yearsJust use
std::array
,std::string
and an initializer list.
-
-
Ian004 over 9 yearsThanks everyone, I have a much better understanding now!