I want to create an array that is a private static data member with a for loop but it does not compile
in the header it is declared in the private zone: static int tableau[2]
in the cpp file i do this
int classe::tableau[2]= {for (int i=0;i<2;++i) {tableau[i]=0;};};
It does not work but if I do this int classe::tableau[2]= {0,0};
then it works. It is a simplified example but in reality I need to use a big
array this is why i need the for loop.
is probably trying to define a member of the class. (i've never seen a data member after the class name, and colons before, but given the way definitions of functions work it would make sense.)
So when you put {0,0}, that is legal because {0,0} represents an array. But when you put
1 2 3
int classe::tableau[2] = {
for(int i = 0; i < 2; ++i){tableau[i] = 0;}
}
you would be setting the data member to be equal to an expression.
What you might do is have a function to initialize the array:
1 2 3 4 5
void classe::makeTableau(int * tableau, int tSize){
for(int i = 0; i < tSize; ++i){
tableau[i] = 0;
}
}
If U want to initialize the static array to zero, then U need not to do it explicitly as "external" and "static" variables are initialized to zero iff not initialized explicitly.
Acutally i don't want to have it set to zero but I am taking a simplified example to understant how to initialize a private static member array with
a for loop
#include<iostream>
usingnamespace std;
class A
{
private:
staticint statPriArray[5];
public:
staticint statPubArray[5];
staticvoid setArray();
staticvoid getArray();
};
class B
{
public:
void getArray()
{
cout<<"Member of Public Static Array of A"<<endl;
for(int i =0; i <5;i++)
{
cout<<A::statPubArray[i]<<endl;
}
/* This will not compile as statPubArray is a member of A.
for(int i =0; i <5;i++)
{
cout<<statPubArray[i]<<endl;
}
*/
/* This will not compile as statPriArray is a static member of A but private one.
for(int i =0; i <5;i++)
{
cout<<A::statPriArray[i]<<endl;
}
*/
}
};
int A::statPriArray[] = {0};
int A::statPubArray[] = {0};
void A::setArray()
{
cout<<"Setting both Private as well as Public Static Array"<<endl;
for(int i =0; i <5;i++)
{
A::statPriArray[i] = i+1;
A::statPubArray[i] = i+5;
/*
///Also can be use as below as both member of A
statPriArray[i] = i+1;
statPubArray[i] = i+1;
*/
}
}
void A::getArray()
{
cout<<"Member of Public Static Array"<<endl;
for(int i =0; i <5;i++)
{
cout<<statPubArray[i]<<endl;
}
cout<<"Member of Private Static Array"<<endl;
for( i =0; i <5;i++)
{
cout<<statPriArray[i]<<endl;
}
}
int main()
{
A::getArray();
A::setArray();
A::getArray();
B* b = new B();
b->getArray();
return 0;
}