2009-10-05 72 views
1

我們如何聲明非靜態常量數組作爲類的屬性?聲明非靜態常量數組作爲類成員

下面的代碼產生編譯錯誤

'測試:: X':成員無法初始化

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

public: 
    Test() 
    { 
    } 
}; 
+0

我需要存儲一些編譯時可用的配置數據。我希望將其放置在只讀存儲區域。 – Vadakkumpadath 2009-10-05 10:35:06

回答

3

你應該閱讀this already posted question。由於無法做你想做的事,所以解決方法是使用std :: vector。

+0

Thaks回覆。但是這種解決方案在數組的情況下是不可能的。當我們初始化數組時,我們將得到另一個編譯錯誤(「不能指定數組的顯式初始化器」)。 – Vadakkumpadath 2009-10-05 09:23:37

+0

我編輯了我的回覆。我連接了錯誤的問題。請再看一遍。 – Ashwin 2009-10-05 09:33:56

+0

'std :: vector'不一樣。它在堆上分配內存。 – 2009-10-05 10:07:32

1

您可以使用來自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 
}; 
0

使用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定義了大小,開始和結束等迭代器和標準容器方法。

+0

數組具有迭代器和標準方法,如size/begin/end。不需要爲一個簡單的課程使用提升。 – 2009-10-05 10:33:26

+0

你說得對。但是在任何tr1實現之前,我都在使用boost。 – Arpegius 2009-10-05 11:04:01