c++ basic array initialization from initializer list

前端 未结 2 724
失恋的感觉
失恋的感觉 2021-01-28 01:19

I\'m beginner to c++

I think this is trivial question but I didn\'t find answer

why this code gives an error ? while if we intialized the array in one line byt

2条回答
  •  温柔的废话
    2021-01-28 02:06

    Arrays do not have assignment operators. You have to copy element by element from the source array to the destination array for example by means of standard algorithm std::copy or using standard C function memcpy or writing your own loop for the task. Or you can set individual elements of an array using the subscript operator.

    However the Standard allows to initialize arrays with initializer lists as any other aggregates when they are defined

    byte x[] = { 78, 82 }; // valid
    x = { 78, 82 }; // compilation error
    

    Also this statement

    cout << x << endl;
    

    does not make sense because this array is not zero-terminated that can result in undefined behaviour.

    However you can use standard class std::array that has the copy assignment operator because it is a class and the compiler implicitly generates this operator for it.

    For example

    #include 
    #include 
    
    typedef unsigned char byte;
    
    int main() 
    {
        std::array x;
        x = { { 78, 82 } };
    
        std::cout.write( reinterpret_cast( x.data() ), x.size() ) << std::endl;
    }    
    

提交回复
热议问题