Error while trying to use const int std::array

This question already has an answer here:

  • constant arrays 3 answers

  • How are you going to assign array values to const int elements? You should initialize them during declaration.

    #include <array>
    
    using namespace std;
    
    int main() {
        array<const int, 4> vals{1, 2, 3, 4};
    
        return 0;
    }
    

    Without any initialization, your sample is similar to invalid const declaration:

    const int a;
    

    Since std::array itself can not be updated, I suppose the below code would be clearer for understanding.

    #include <array>
    
    using namespace std;
    
    int main() {
        const array<int, 4> vals{1, 2, 3, 4};
    
        return 0;
    }
    

    It is due to the fact that a constant object must be initialized when it is defined. However using this declaration

    array<const int, 4> vals;
    

    you did not provide an initializer.

    Consider the following program

    #include <iostream>
    #include <array>
    
    int main() 
    {
        int x = 42;
        std::array<const int, 4> vals = { { 1, 2, 3, 4 } };
    
        for ( int x : vals ) std::cout << x << ' ';
        std::cout << std::endl;
    
        return 0;
    }
    

    Its output is

    1 2 3 4
    
    链接地址: http://www.djcxy.com/p/66748.html

    上一篇: 良好的PHP ORM库?

    下一篇: 尝试使用const int std :: array时出错