2d array initialization and inaccessible data members.

So I am writing a class that will randomly select a colour from an array of colours. The problem is that I can't seem to initialize the constructor with the values I want, and apart from that in another function VC++ is telling me that two data members are inaccessible.

Colour.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef POINT_H
#define POINT_H

class Colour
{
public:
	
	Colour(void);
	~Colour(void);
    
private:

	int colour[3];
	int colour_list[12][3];	
	int *getColour(void);


};
#endif  



Colour.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "Colour.h"
#include <ctime>
#include <cstdlib>

Colour::Colour(void)
{
	colour_list[12][3]  = { {201,47,39},
				{156,0,37},
				{216,24,73},
				{200,33,102},
				{251,81,55},
				{250,141,24},
				{255,240,115},
				{239,233,197},
				{140,216,233},
				{22,175,235},
				{8,81,140},
				{31,8,140},
			      };	

}

Colour::~Colour(void){}

int Colour::*getColour(void)
{
	int column = int(13*rand()/(RAND_MAX + 1.0)); 

	for(int index=0; index<3; index++)
		colour[index] = colour_list[column][index];
	
}



If in the header file I change the data members to public and static it overcomes the latter problem, however that solution doesn't seem right to me.

I'm assuming it's some silly mistake but I come from a Java background and have little experience with c++.

Thanks,
Bruynz.
Last edited on
In your colour constructor, colour_list[12][3]=... is an assignment to the [12][3] item of the colour_list array. Problem #1, [12][3] does not exist - the highest values are [11][2], as C++ arrays are 0-based. Problem #2, this is the syntax for declaring and initializing a whole array in one go. But you have already declared colour_list as a data member of Colour, so you can't initialize it like this here; you would have to do it item by item.

However, what it looks as if you want to do is to have the same colour_list for all instances of Colour. So you should make colour list a static member of the class. Then the initializer should go in the definition of the static member, which comes in Colour.cpp after the header files:
int Colour::colour_list[12][3] = .... (put your initialization list here), and not in the class declaration - but you still need the declaration static int colour_list[12][3]; in the class declaration.
Topic archived. No new replies allowed.