CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2008
    Location
    *****, Nigeria
    Posts
    40

    initializing array in class

    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.

    Code:
    #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
    Last edited by ch0co; July 6th, 2008 at 10:17 AM.

  2. #2
    Join Date
    May 2008
    Posts
    96

    Re: initializing array in class

    You've got a couple of significant syntax errors.

    To declare a static field:
    Code:
    // foo.hpp
    
    #ifndef FOO_HPP
    #define FOO_HPP
    
    class Foo
      {
      static int fooey;
      };
    
    #endif
    Code:
    // 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:
    Code:
    // 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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured