-
April 5th, 2009, 07:00 AM
#1
Array Declaration in class
hey guys,
I want to create a class that has an array of unsigned integers whereby the constructor takes in a single unsigned integer to be the size of the array, i.e.
So for I have, in myclass.h
class myclass
{
private:
unsigned int grades[]; //(i)
public:
myclass(unsigned int Size)
};
In myclass.cpp
#include "myclass.h"
myclass:myclass(unsigned int Size)
{
grades = unsigned int[Size]; //(ii)
}
int main(void)
{
myclass Test(10);
return 0;
}
When I build this (In Visual Studio 2005 .NET), I can the following error messages,
in reference to (i)
warning C4200: nonstandard extension used : zero-sized array in struct/union
in reference to (ii)
error C2062: type 'unsigned int' unexpected
Where am I going wrong??
Thanks in Advance,
David
-
April 5th, 2009, 07:57 AM
#2
Re: Array Declaration in class
Code:
unsigned int grades[];
Your array has no size.
Code:
unsigned int grades[10];
now it has. But what you are trying should look like this:
Code:
unsigned int *grades;
grades = new int[10];
...
delete []grades.
-
April 5th, 2009, 10:21 AM
#3
Re: Array Declaration in class
If you write it that way, you'll have to define the destructor, copy constructor, and operator= as well in order to ensure the class objects don't become corrupted. (Alternatively you can simply define the destructor and disable the other two by declaring them private.)
If you want to save all that effort, declare grades as a std::vector<unsigned int>. Then the default-generated versions of each of those functions will be good enough.
-
April 6th, 2009, 01:02 AM
#4
Re: Array Declaration in class
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|