2014-05-07 77 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才能使用它。