2012-02-16 78 views
1

在std ::阵列 即时编译该代码的std ::阵列C++ 11初始化语法错误​​

#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; 
} 

但它编译时,当我做到这一点上得到

no match for ‘operator=’ in ‘myarr = {1, 5, 2, 3, 4}’ 

错误同一行

array<int, 5> myarr = {1,5,2,3,4}; 

如何在seprate行赋值

我需要在类构造函数中分配值我该怎么做?

class myclass 
{ 
    myclass() 
    { 
    myarr = {1,2,3,4,5}; /// how to assign it // it gives errors 
    } 
}; 
+0

下面的答案适用于您确实需要在施工后分配数组,但实际上很少需要。对于构造函数,您可以并应该使用初始化列表而不是赋值,如C++常见问题解答中所述:http://www.parashift.com/c++-faq/init-lists.html。 – 2012-08-16 18:20:10

回答

6

而不是你需要两个大括号。

myarray = {{1,2,3,4,5}}; 
-1

您需要一个临时对象。

class myclass 
{ 
    myclass() 
    { 
    myarr = std::array<int,5>{1,2,3,4,5}; 
    } 
}; 

语法var = { values, ... }仅对初始值设定项有效。但是你在这里做一个任务,而不是初始化。 C++ 11在这里改变的是,你现在可以在任何类类型(在定义了合适的构造函数的地方)进行这种类型的初始化,然后它只在POD类型和数组上工作。

+2

“*之前它只适用于POD类型和数组*”不完全;之前它只在_aggregate_类型上工作。 – ildjarn 2012-02-16 16:50:17

+2

-1。错误。填料。 – 2012-02-16 18:06:35