How would I initialize a private array where that one hundred items each equal a two-item array such as {-1, 0}. My code below obviously does not work since I am asking you all.
example.h:
#ifndef EXAMPLE
#define EXAMPLE
class Example {
private:
char grid[10][10];
public:
Example();
};
#endif
example.cpp:
#include "example.h"
#include <iostream>
Example::Example() : grid({-1, 0}) {}
This is not currently possible with C++. In C++0x it will be possible with braces, like
Example::Example() : grid{{-1, 0}} {}
And for the time being, you can wrap that array in a class, without any performance loss (the array will still be a normal, native multidimensional array)
class Example {
private:
struct data {
char grid[10][10];
static data newData() {
data d = {{
{ -1, 0 }, { -2, 1 } /* ... */
}};
return d;
}
} d;
public:
Example() : d(data::newData()) { }
};
Unfortunately you can't initialise members like this. You have to manually assign to each value in the constructor body using std::fill (or good old = and a loop).
This will change in C++0x, though, in which you can write code like the code you posted.
(Also, you have a mismatch in your question. You declare an array of 10 arrays of 10 chars each, but your initialisation attempt bears no resemblance to that use case whatsoever. It's not really clear exactly what you're trying to do, but since you'll have to use a different approach anyway I suppose it doesn't really matter for this answer.)
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