什么是非静态2D阵列的正确初始值设定项?

问题描述 投票:0回答:1

Visual Studio允许:int a [3] [3] = {0};对于BOTH局部变量和非静态类变量。但是,GCC只允许这个局部变量,但需要int a [3] [3] = {{0}};用于类变量初始化。海湾合作委员会是否过于限制或VS是否宽容?

#include <iostream>
using namespace std;

class InitArray {
 public:
   InitArray();
   void PrintArray() const;
 private:
   int a[3][3] = { 0 };       // compiles in Visual Studio 2017, but not GCC
                              // modify to = { {0} }; to compile in GCC
InitArray::InitArray() {
   PrintArray();
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         a[i][j] = 1;
      }
   }
}

void InitArray::PrintArray() const {
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         cout << a[i][j] << " ";
      }
      cout << endl;
   }
}

int main() {
   InitArray A;
   A.PrintArray();
   int a[3][3] = {0};          // OK in BOTH compilers
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         cout << a[i][j] << " ";
      }
      cout << endl;
   }

   return 0;
}
c++11 variables initializer-list non-static
1个回答
1
投票

您只编码内部化数组中的第一个单元格,更改行

int a[3][3] = {0}; 

 int a[3][3] = {1};

并查看输出,只有第一个单元格为1,其余单元格为零。

关于编译问题,我正在与GCC编译并且都为我编译。初始化类型之间的区别在于

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

将编译,你会得到

1 2 3 
4 5 0 
0 0 0

但是int b [3] [3] = {{1,2,3,4}};因为而不会编译

'int [3]'的初始化程序太多会发生这种情况,因为{{}}只会初始化a [3] [3]矩阵中的第一个[3]数组。如果你想初始化它,你需要像这样调用它:

int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
© www.soinside.com 2019 - 2024. All rights reserved.