This is absolutely wrong to initialize the whole array like this :
upgradeCosts[4][4] = {{150, 250, 900, 1800},
{100, 200, 600, 1200},
{200, 350, 1200, 2000},
{150, 300, 1000, 1900}};
Because you just set the [4][4]
element, not the whole array. This what the Excess elements in scalar initializer
error refers to. An int
is a scalar, it can only be initialised with 1 value, yet you attempt to initialise it with 16 values.
To correct this you would assume you could do this:
bool HelloWorld::init()
{
upgradeCosts = {{150, 250, 900, 1800},
{100, 200, 600, 1200},
{200, 350, 1200, 2000},
{150, 300, 1000, 1900}};
}
However this will not work because upgradeCosts
has already been default initialised during the construction of HelloWorld
and cannot be initialised again.
A naive solution to this would be like the following:
bool HelloWorld::init()
{
int data[4][4] = {{150, 250, 900, 1800},
{100, 200, 600, 1200},
{200, 350, 1200, 2000},
{150, 300, 1000, 1900}};
for(int i = 0;i < 3;i++)
for(int j = 0;j < 3;j++)
upgradeCosts[i][j] = data[i][j];
...
}
However, this involves pointless copying. A better solution would be to move the array initialisation out of the init
method altogether. You can do this by either just initialising the array in the header file:
// hpp file
class HelloWorld
{
private:
int upgradeCosts[4][4] = {{150, 250, 900, 1800},
{100, 200, 600, 1200},
{200, 350, 1200, 2000},
{150, 300, 1000, 1900}};
public:
bool init();
};
Or you could initialise it in the constructor of HelloWorld
:
// hpp file
class HelloWorld
{
private:
int upgradeCosts[4][4];
public:
HelloWorld();
bool init();
};
// cpp file
HelloWorld::HelloWorld()
: upgradeCosts{{150, 250, 900, 1800},
{100, 200, 600, 1200},
{200, 350, 1200, 2000},
{150, 300, 1000, 1900}}
{ }
Or if you know that your upgradeCosts
should be the same across all instances of HelloWorld
you can use a static
member and initialise it like below :
// hpp file
class HelloWorld
{
private:
const static int upgradeCosts[4][4];
public:
bool init();
};
// cpp file
const int HelloWorld::upgradeCosts[4][4] = {{150, 250, 900, 1800},
{100, 200, 600, 1200},
{200, 350, 1200, 2000},
{150, 300, 1000, 1900}};