Out of curiousity, do your difficulty values ever change? If you simply need the values 1, 2, and 3 then perhaps you could just use constants, an enum or just a plain
int?
As for your compiler error, here's an explanation (assuming you really do want an array with changable values and not just constants):
You've declared 'difficulty' in your class here
int* difficulty;
but on line 338, you're attempting to de-reference the pointer and assign an initialiser list:
difficulty[3] = {1,2,3};
There are several problems with this:
1)
difficulty[3]
is an
int - the subscript [] operator de-references your 'difficulty' pointer and iterates to a position in memory which is 3 steps beyond
*difficulty
(Array Subscript Syntax/Notation and Dereferencing both work in the same way - see
http://www.c-faq.com/aryptr/ for more info)
2) You're allocating difficulty as size 3, although difficulty[3] is the 4th element
3)
{1,2,3}
is an array initialiser, which can only be used as part of initialisation in-line for a fixed-size array
4) You can't initialise a pointer using an array initialiser
5) Even if difficulty was an ordinary fixed-size array, you still can't initialise a non-static class-member array using an array initialiser
If you want to just keep it simple, then this should be enough:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class foo
{
// Using an array instead of a pointer
int difficulty[3];
public:
foo()
{
difficulty[0] = 1;
difficulty[1] = 2;
difficulty[2] = 3;
}
};
|
If you have a C++11 compiler, you could be a little bit more "clever" and generic - e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <algorithm>
class foo
{
// Just a convenience for using as a "lookup table"
static const int my_table[3];
// Using an array instead of a pointer
int difficulty[3];
public:
foo()
{
// Copy from the lookup table into the difficulty array
std::copy(std::begin(my_table), std::end(my_table), std::begin(difficulty));
}
};
// Initialising the lookup table with pre-set values.
// Initialisation of static member is allowed using Array Initialiser
const int foo::my_table[3] = { 1, 2, 3 };
|
In the code above, "my_table" is being used as a lookup-table to initialise the difficulty array (which is a fixed size of 3 instead of being declared as a pointer using a new'ed block of memory).
The constructor is copying the content of the lookup into the difficulty array using
std::copy()
.
-
std::begin()
and
std::end()
are little clean "helper" functions which simply point to the beginning and (one past the) end of the fixed-size array (those functions work equally well for strings, vectors, lists, deques, etc)