I am trying to initialize a member array in the default constructor of a class which I've created. However, nothing I've tried has worked. I'm quite new to c and programming in general, and I haven't found the answer I was looking for online yet. In my .hpp file I have:
class thing
{
private:
std::string array[8][8];
public:
thing();
};
And in the corresponding .cpp file I have:
thing::thing()
{
array =
{
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"}
};
//error: Array type 'std::string [8][8]' is not assignable
}
I've also tried the following:
Board::Board()
{
std::string array[8][8] =
{
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"}
};
}
Doing it this way doesn't cause any compiler errors, but it doesn't seem to actually work. When I try to cout the elements in the array I get nothing. Is there a way to do what I want to do?
CodePudding user response:
Either use a constructor initializer list, or use a default member initializer.
#include <string>
class thing {
std::string array[8][8];
public:
thing();
};
thing::thing()
: array{
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
}
{ }
class thing2 {
std::string array[8][8] = {
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
};
};
int main() {
thing t;
(void)t;
thing2 t2;
(void)t2;
}