无法从括号括起来的初始化程序列表进行转换 [英] Could not convert from brace-enclosed initializer list
本文介绍了无法从括号括起来的初始化程序列表进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编译下面的代码,但我一直遇到错误
could not convert '{{1, 2}, {5, 6}}' from '<brace-enclosed initializer list>' to 'Class1'
.我正在编译-std=c++11
中的代码.我的初始化错误吗?
I am trying to compile the code below but I keep running into the error
could not convert '{{1, 2}, {5, 6}}' from '<brace-enclosed initializer list>' to 'Class1'
. I am compiling the code in -std=c++11
. Is my initialization wrong?
class Class1
{
public:
vector<vector<int> > a;
Class1(vector<vector<int> > p)
{
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
a[i][j] = p[i][j];
}
};
int main()
{
Class1 ClassValue = {{ 1, 2, },{ 5, 6 } };
return 0;
}
推荐答案
首先,将行更改为:
Class1 ClassValue ({{ 1, 2 },{ 5, 6 } });
第二件事是,当您写入不存在的内存时,构造函数无效.而是使用:
Second thing is your constructor is invalid, as you write to non-existing memory. Instead, use:
Class1(vector<vector<int> > p):a(p){}
注释后由于您不会第二次复制,因此此注释会更好(更快).
EDIT AFTER COMMENT: This one will be better (faster), as you don't copy second time.
Class1(vector<vector<int> > p):a(move(p)){}
这篇关于无法从括号括起来的初始化程序列表进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文