C++ 无法转换大括号括起来的初始化列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22807427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:13:55  来源:igfitidea点击:

Cannot convert Brace-enclosed initializer list

c++arraysvariable-assignment

提问by user3481693

I declare a table of booleans and initialize it in main()

我声明了一个布尔值表并将其初始化 main()

const int dim = 2;
bool Table[dim][dim];

int main(){

     Table[dim][dim] = {{false,false},{true,false}};
     // code    
     return 0;
}

I use mingwcompiler and the builder options are g++ -std=c++11. The error is

我使用mingw编译器,构建器选项是 g++ -std=c++11. 错误是

cannot convert brace-enclosed initializer list to 'bool' in assignment`

无法将大括号括起来的初始值设定项列表转换为赋值中的“bool”

回答by Some programmer dude

Arrays can only be initialized like that on definition, you can't do it afterwards.

数组只能像定义那样初始化,之后就不能再做。

Either move the initialization to the definition, or initialize each entry manually.

要么将初始化移动到定义,要么手动初始化每个条目。

回答by user3488743

First, you are trying to assign a concrete element of array instead assigning the full array. Second, you can use initializer list only for initialization, and not for assignment.

首先,您试图分配数组的具体元素而不是分配完整的数组。其次,您只能将初始化列表用于初始化,而不能用于赋值。

Here is correct code:

这是正确的代码:

bool Table = {{false,false},{true,false}};

回答by Ankur

You can use memset(Table,false,sizeof(Table))for this.it will work fine.

您可以memset(Table,false,sizeof(Table))为此使用它。它会正常工作。

Here is your complete code

这是您的完整代码

#include <iostream>
#include<cstring>
using namespace std;

   const int dim = 2;
    bool Table[dim][dim];

    int main(){

         memset(Table,true,sizeof(Table));
         cout<<Table[1][0];
// code    
return 0;
    }