std::array c++11 initializer syntax error

ぃ、小莉子 提交于 2019-12-11 10:44:39

问题


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

回答1:


Instead of the one pair of braces you need two.

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



回答2:


You need a temporary object.

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

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.



来源:https://stackoverflow.com/questions/9314727/stdarray-c11-initializer-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!