std::array c++11 初始化语法错误
std::数组 遇到
no match for ‘operator=’ in ‘myarr = {1, 5, 2, 3, 4}’
我在编译此代码时
#include <iostream>
#include <array>
using namespace std;
int main(int argc, char const *argv[])
{
array<int, 5> myarr;
myarr = {1,5,2,3,4};
for(auto i : myarr)
{
cout << i << endl;
}
return 0;
}
错误,但当我在同一行上执行此操作时它会编译
array<int, 5> myarr = {1,5,2,3,4};
如何在单独的行上分配值
我需要在类构造函数中分配值我该怎么做?
class myclass
{
myclass()
{
myarr = {1,2,3,4,5}; /// how to assign it // it gives errors
}
};
the std::array
im getting
no match for ‘operator=’ in ‘myarr = {1, 5, 2, 3, 4}’
error when compiling this code
#include <iostream>
#include <array>
using namespace std;
int main(int argc, char const *argv[])
{
array<int, 5> myarr;
myarr = {1,5,2,3,4};
for(auto i : myarr)
{
cout << i << endl;
}
return 0;
}
but it compiles when i do it on the same line
array<int, 5> myarr = {1,5,2,3,4};
how to assign values on the seprate line
i need to assign values in the class constructor how can i do it ?
class myclass
{
myclass()
{
myarr = {1,2,3,4,5}; /// how to assign it // it gives errors
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要两副牙套,而不是一对。
Instead of the one pair of braces you need two.
你需要一个临时对象。
语法
var = { value, ... }
仅对初始值设定项有效。但您在这里进行分配,而不是初始化。 c++11 此处的更改是,您现在可以对任何类类型(定义了适当的构造函数)执行这种类型的初始化,而之前它仅适用于 POD 类型和数组。You need a temporary object.
The syntax
var = { values, ... }
is only valid for initializers. But you do an assignment here, not an initialization. What c++11 changed here is that you can do this type of initialization now for any class type (where the appropriate constructor is defined), before it worked only on POD types and arrays.