How can we declare a non static const array as an attribute to class. Following code produces compilation error (“'Test::x' : member could not be initialized”)?
class Test
{
public:
const int x[10];
public:
Test()
{
}
};
How can we declare a non static const array as an attribute to class. Following code produces compilation error (“'Test::x' : member could not be initialized”)?
class Test
{
public:
const int x[10];
public:
Test()
{
}
};
You should read this already posted question. Since it is not possible to do what you want, the workaround is to use an std::vector.
You could use array
class from tr1.
class Test
{
public:
const array<int, 10> x;
public:
Test(array<int,10> val) : x(val) // the only place to initialize x since it is const
{
}
};
array
class could be simplistically represented as follows:
template<typename T, int S>
class array
{
T ar[S];
public:
// constructors and operators
};
Using boost::array (the same as tr1) it will looks like:
#include<boost/array.hpp>
class Test
{
public:
Test():constArray(staticConst) {};
Test( boost::array<int,4> const& copyThisArray):constArray(copyThisArray) {};
static const boost::array<int,4> staticConst;
const boost::array<int,4> constArray;
};
const boost::array<int,4> Test::staticConst = { { 1, 2, 3 ,5 } };
The extra code static member is needed because { { 1, 2, 3 ,5 } }
is invalid in initialization list.
Some advantages is that boost::array have defined iterator and standard container methods like size, begin and end.