2014-05-07 78 views
1

我想初始化數組car.places [2] [3] ,但數組中始終爲零。 請誰能告訴我什麼I'm做錯了, 這裏是代碼:C++錯誤初始化數組

#include <iostream> 
#include <string> 

using namespace std; 

class reserv 
{ 
public: 
    int places[2][3]; 
} car; 


int main() { 

car.places[2][3] = (
      (1, 2, 3), 
      (4, 5, 6) 
     ); 

for(int i=0;i<2;i++) 
{ 
    for(int j=0;j<3;j++) 
    { 
     cout << i << "," << j << " " << car.places[i][j] << endl; 
    } 
} 

    return 0; 
} 

我得到這樣的警告形成編譯:

>g++ -Wall -pedantic F_car_test.cpp 
F_car_test.cpp: In function 'int main()': 
F_car_test.cpp:16:11: warning: left operand of comma operator has no effect [ 
-Wunused-value] 
     (1, 2, 3), 
     ^
F_car_test.cpp:16:14: warning: right operand of comma operator has no effect 
[-Wunused-value] 
     (1, 2, 3), 
      ^
F_car_test.cpp:17:11: warning: left operand of comma operator has no effect [ 
-Wunused-value] 
     (4, 5, 6) 
     ^
F_car_test.cpp:17:14: warning: right operand of comma operator has no effect 
[-Wunused-value] 
     (4, 5, 6) 
      ^

由於提前,

+0

「Theres在數組中始終爲零」您是什麼意思?你只得到零? –

+0

沒關係!我讀錯了.. –

+1

你沒有初始化數組,你正在分配給它。你不能分配給數組。 – Barmar

回答

1

你在沒有循環的聲明之後不能做到這一點。

這裏是如何做到這一點在一個循環:

for (int i = 0; i < 2; ++i) { 
    for (int j = 0; j < 3; ++j) { 
     car.places[i][j] = 1 + 3 * i + j; 
    } 
} 
1

不能初始化一旦創建了一個結構/類的對象;它被稱爲初始化的原因。的類RESERV(或更精確地對象轎廂的)的數據成員初始化的地方是這樣

#include <iostream> 

struct reserv 
{ 
    int places[2][3]; 
} car = {{{1, 2, 3}, {4, 5, 6}}}; 


int main() 
{ 
    for(int i = 0; i < 2; ++i) 
    { 
    for(int j = 0; j < 3; ++j) 
    { 
     std::cout << i << "," << j << " " << car.places[i][j] << std::endl; 
    } 
    } 
} 
0

此記錄

car.places[2][3] 

表示元件的地方[2] [3]。

該數組已被創建爲您在全局名稱空間中定義的對象車的一部分。

寫,而不是

class reserv 
{ 
public: 
    int places[2][3]; 
} car = { { 
      {1, 2, 3}, 
      {4, 5, 6} 
     } }; 
0

在C++中,你只能在聲明初始化初始化列表陣列。因爲在這種情況下你的數組是一個類成員,你可以(也應該)在構造函數中完成它。

reserv::reserv():places{{1,2,3},{4,5,6}}{}; 

您必須啓用std=c++0x才能使用它。