Click to See Complete Forum and Search --> : initializing array in class


ch0co
July 6th, 2008, 05:05 AM
I have a problem with initializing an array from within a class; all I'm trying to do is generate 7 random numbers preceding with the numbers in an array then seperate with comma's.



#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

class Create
{

public:

Create()
{
Loop = 6; // did this because it doesnt allow me to
// initialize int Loop = 6; in either public: or private:


while(0 < Loop)
{

cout << Numbers[Loop];


for (int i = 0; i < 7; i++)
{


create[i] = (rand() %8) + 1;
cout << create[i];
if ( i == 6)
{
cout << ",";
}

}
Loop--;
}

}
protected:
int create[6];
int Loop;
int Numbers[7] = {234803, 234805, 234802};


};



int main(int nNumberofArgs, char* pszArgs)
{
srand(time(0));

Create New;
system("PAUSE");
return 0;

}


I have a version that works but I think it has poor coding.
Or, is there a way I could tell rand() to generate 7 random numbers in length.

Regards,
Richard Aberefa

Duoas
July 6th, 2008, 06:45 AM
You've got a couple of significant syntax errors.

To declare a static field:

// foo.hpp

#ifndef FOO_HPP
#define FOO_HPP

class Foo
{
static int fooey;
};

#endif


// foo.cpp

#include "foo.hpp"

int Foo::fooey = 6;

I've separated them into individual files, but if your class and definition are all declared in one file then stick them all together:

// myprog.cpp

...

class Foo
{
static int fooey;
};

int Foo::fooey = 6;

int main()
{
...
}

That should fix things enough to keep you going.

Hope this helps.