Reputation: 692
I'm relearning C++ and I'm having some trouble with arrays in classes. Here's a simplified version of what I'm working with
class Class
{
private:
string array[2];
public:
Class()
{
array[2] = {"Hello", "World"};
}
void printOut(int x)
{
cout << array[x];
}
Visual Studio has an error on the first brace in the array initialization in the constructor (i.e. {"Hello", "World"}; which says "Error: expected an expression." However, this problem does not occur when I initialize any other variable (not arrays).
I would have simple initialized the array values when I declared the array in the private section of the class as shown below.
class Class
{
private:
string array[2] = {"Hello", "World"};
But Visual Studio gives an error on the equals sign saying "Error: data member initialization is now allowed." This error does occur any time I try to initialize the variables at the same time they are declared in the private section of the class.
Any help or advice would be appreciated, thank in advance.
Upvotes: 0
Views: 2091
Reputation: 53047
Arrays can only be initialized using that syntax, not assigned. You have to initialize it in the constructor's initialization list:
Class() : array{"Hello", "World"} {}
Alternatively, use std::array
which can be assigned.
std::array<string, 2> array;
Class()
{
array = {{ "Hello", "World" }};
}
Another:
Class()
{
array[0] = "Hello";
array[1] = "World";
}
Upvotes: 3