【问题标题】:Declaring a non static const array as class member将非静态 const 数组声明为类成员
【发布时间】:2009-10-05 09:08:45
【问题描述】:

我们如何将非静态 const 数组声明为类的属性?

以下代码产生编译错误

'Test::x' : 无法初始化成员

class Test
{
public:
    const int x[10];

public:
    Test()
    {
    }
};

【问题讨论】:

  • 我需要存储一些在编译时可用的配置数据。我希望将其放置在只读存储区域中。

标签: c++ arrays class static constants


【解决方案1】:

您应该阅读this already posted question。由于不可能做你想做的事,解决方法是使用 std::vector。

【讨论】:

  • 感谢您的回复。但是在数组的情况下,该解决方案是不可能的。当我们初始化数组时,我们会得到另一个编译错误(“无法为数组指定显式初始化程序”)。
  • 我已经编辑了我的回复。我链接了错误的问题。请再看一遍。
  • std::vector 不一样。它在堆上分配内存。
  • 我希望它在存储的只读区域中初始化。 std::vector 可以吗?
  • 您不需要在只读区域中分配内存的动态分配对象。这是不可能的,只读区域的内存需要在编译时初始化,但在编译时不知道要创建多少对象。
【解决方案2】:

您可以使用 tr1 中的 array 类。

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 类可以简单表示如下:

template<typename T, int S>
class array
{
    T ar[S];
public:
    // constructors and operators
};

【讨论】:

    【解决方案3】:

    使用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 } };
    

    需要额外的代码静态成员,因为{ { 1, 2, 3 ,5 } }在初始化列表中无效。

    一些优点是 boost::array 定义了迭代器和标准容器方法,如大小、开始和结束。

    【讨论】:

    • tr1 中的数组具有迭代器和标准方法,例如 size/begin/end。无需为一个简单的类使用 boost。
    • 你说得对。但我在任何 tr1 实现之前到处都使用 boost。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多