Feb 25, 2014 at 4:47am UTC
I am trying to initialize a class with an array, however I keep getting an error in my int main.
Class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class testclass
{
public :
int testnum[10];
testclass(int testnum[])
{
BuildArray(testnum);
}
private :
void BuildArray(int num[])
{
for (int i=0;i<10;i++)
{
testnum[i]=num[i];
}
}
};
I've tried this:
testclass test={{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}};
And this:
testclass test={0,0,0,0,0,0,0,0,0,0};
And finally this:
testclass test={{0,0,0,0,0,0,0,0,0,0}};
Can someone please tell me what I'm doing wrong?
Last edited on Feb 25, 2014 at 4:47am UTC
Feb 25, 2014 at 4:58am UTC
I:\CodeBlocks\Games\SDL2\Platformer Game\main.cpp|44|error: could not convert '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}' from '<brace-enclosed initializer list>' to 'testclass' |
Feb 25, 2014 at 5:18am UTC
I would rather use a brace-enclosed initializer list, but thanks for the feedback.
Feb 25, 2014 at 11:25pm UTC
Well of course it barfs
int n[10] = {};
should be
int n[10];
and I'm trying to keep testclass as a class..
How can I make so I dont have to do this:
1 2
int testvar[10]={0,1,2,3,4,5,6,7,8,9};
testclass test={testvar};
but can do something like this:
testclass test={{0,1,2,3,4,5,6,7,8,9}};
Last edited on Feb 25, 2014 at 11:31pm UTC
Feb 26, 2014 at 12:55am UTC
Thanks for the help I finally have this working.
Final Code:
1 2 3 4 5 6 7 8 9 10 11
class testclass
{
public :
int testnum[10];
testclass(std::initializer_list<int > testnum)
{
auto i= testnum.size()<=10 ? testnum.end() : testnum.begin()+10;
std::copy(testnum.begin(),i,this ->testnum);
}
};
Last edited on Feb 26, 2014 at 1:38am UTC
Feb 26, 2014 at 1:21am UTC
Line 8 in your code has no effect. If the initializer_list happens to contain more values than this->testnum can hold, the call to std::copy will happily write to memory it has no business writing to.
Feb 26, 2014 at 1:38am UTC
Thanks for pointing out, fixed.