How can we declare a non-static const array as an attribute to class?
我们如何将非静态const数组声明为类的属性?
Following code produces compilation error
以下代码产生编译错误
'Test::x' : member could not be initialized
'test :: x':无法初始化成员
class Test
{
public:
const int x[10];
public:
Test()
{
}
};
3 个解决方案
#1
3
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.
你应该阅读这个已发布的问题。由于不可能做你想要的,解决方法是使用std :: vector。
#2
1
You could use array
class from tr1.
您可以使用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
};
#3
0
Using boost::array (the same as tr1) it will looks like:
使用boost :: array(与tr1相同),它看起来像:
#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.
需要额外的代码静态成员,因为{{1,2,3,5}}在初始化列表中无效。
Some advantages is that boost::array have defined iterator and standard container methods like size, begin and end.
一些优点是boost :: array定义了迭代器和标准容器方法,如size,begin和end。
#1
3
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.
你应该阅读这个已发布的问题。由于不可能做你想要的,解决方法是使用std :: vector。
#2
1
You could use array
class from tr1.
您可以使用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
};
#3
0
Using boost::array (the same as tr1) it will looks like:
使用boost :: array(与tr1相同),它看起来像:
#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.
需要额外的代码静态成员,因为{{1,2,3,5}}在初始化列表中无效。
Some advantages is that boost::array have defined iterator and standard container methods like size, begin and end.
一些优点是boost :: array定义了迭代器和标准容器方法,如size,begin和end。