-
Arrays & Classes
Hi!I want to use an array as a class member.I wrote something like this:
Code:
class my_class{
public:
....
int x;
int array[5];
void function();
.....
}
my_class::my_class()
{
....
x = 0;
array[ 5 ] = { 0,1,2,3,4 };
}
void my_class::function()
{
for( i = 0; i < 5; i++ )
{
if ((something) > array[i] )
{
do something.....;
}
}
}
The compiler (Dev-C++) gave an error with the message "expected priimary - expression before '{' token : in the line // array[ 5 ] = { 0,1,2,3,4 }; // of the constructor.
Any ideas...?
MaRaDoNa
========
-
thou shalt not initialize variables inside of a class.. that is the sole responsibility of the class constructor.
Code:
x = 0; <- not allowed inside a class
array[ 5 ] = { 0,1,2,3,4 }; <- not allowed inside a class
-
array[5] does not exist... array's are 0-based so valid indicies go from 0 up to and including 4 (but not 5). In addition, array[5], if it existed, would be a single element of the array to which you are attempting to assign 5 integers. I'd suggest a loop:
Code:
my_class::my_class()
{
....
x = 0;
for( int i = 0; i < 5; ++i )
array[ i ] = i;
}
-
>> x = 0; <- not allowed inside a class
That is allowed, it is just an assignment instead of an initialization.
-
youre missing a semicolon after the class declaration
>>that is the sole responsibility of the class constructor.
it is in the constructor
-
x=0; is perfectly allowable inside a constructor, the problem is that inside the body of a constructor it's assignment, rather than construction. the correct way of doing this is ctor() : x(0), ... {} here x is constructed with the value 0. As to constructing an array with a list of values I am afraid you are simply out of luck. std::vectors can be constructed with N copies of any value you like. However, if you want each value in the array to be different you need to copy them all in. an ugly but workable solution would be
Code:
my_class::my_class() : x(0)
{
int dummy[] = { 0,1,2,3,4 };
memcpy(array,dummy,sizeof(array)/sizeof(array[0]));
}
-
Just wondering - It is C++ why not to use vector?