2011-02-09 88 views
0

我有一個二維數組,我聲明瞭類私有成員的一部分。當我調用構造函數時,我開始將值分配給2D數組。但每次我這樣做,我都會遇到錯誤C2059。爲了確保沒有其他東西導致了這個錯誤,我註釋掉了這行,並且編譯器把一個二進制文件放在一起。C++類,在構造函數初始化時分配值

tried: 
Variable[row] = { 0, 1, 2, 3}; 
Variable[row][] = { 0, 1, 2, 3}; 
Variable[row][4] = { 0, 1, 2, 3}; 

沒有運氣,任何線索。提前致謝。

+2

什麼是`C2059`錯誤?當然,我可以谷歌它,但我應該谷歌或回答你的問題? – delnan 2011-02-09 15:51:44

+1

你可以添加`Variable`的聲明嗎? – fouronnes 2011-02-09 15:53:50

回答

1

不幸的是,我們還不能正確初始化屬於類成員的數組。我不知道你的聲明是怎麼樣的,但這裏有一個例子:

class X 
{ 
    int Variable[3][4]; 

public: 
    X() 
    { 
     const int temp[][4] = { { 1, 2, 3, 4}, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; 
     const int sz = sizeof(Variable)/sizeof(**Variable); 
     std::copy(*temp, (*temp) + sz, *Variable); 
    } 
}; 
3

此語法僅用於創建對象。

int array[4] = {1, 2, 3, 4}; 

創建數組後,您必須使用循環爲其分配值。

這裏有一個簡單的例子:

class A 
{ 
    int array[4]; 

    public: 
    A() 
    { 
     // Here, array is already created 
     // You can _assign_ values to it 
    } 
}; 

如果你想給當它在構造函數實例它的價值觀,唯一的辦法就是使用初始化列表。不幸的是,你不能用靜態數組來做到這一點。

看到這個this thread.

0

因爲你的問題不夠清楚,我所能做的就是展示一個簡單的例子。

二維數組初始化爲,

//you may "optionally" provide the size of first dimension 
int arr[][4] = { 
      {1,2,3,4}, 
      {11,12,13,14}, 
      {21,22,23,24} 
     }; 

,並acessed爲,

for (int i = 0 ; i < 3 ; ++i) 
{ 
     for (int j = 0 ; j < 4 ; ++j) 
     { 
      cout << arr[i][j] << endl; 
     } 
} 

在ideone在線演示:http://www.ideone.com/KmwOg

你同樣在做什麼?