簡體   English   中英

初始化 std::array<struct, size></struct,>

[英]initialize std::array <struct, size>

我正在嘗試定義和初始化一個結構數組。

#include <iostream>
#include <array>

int main() {
    struct row{
        double a0;
        double a1;
    };

    //method 0: this way works
    row c[2] ={{1.0,2.0},{3.0,4.0}};

    //method 1: declare and initialization in same line 
    //std::array<row, 2> a = { {1.0, 2.0}, {3.0, 4.0} };//error: Excess elements in struct initializer
    std::array<row, 2> a = {{ {1.0, 2.0}, {3.0, 4.0} }}; //double brace


    //method 2, declare, then initialize in different line
    std::array<row, 2> b;
    //b = { {1.0, 2.0}, {3.0, 4.0} };//error: No viable overloaded '='
    b = { { {1.0, 2.0}, {3.0, 4.0} } }; //double brace

    return 0;
}

現在我從這篇文章中找到了雙括號的作品。

只是想知道為什么我們需要額外的大括號來初始化結構數組?

您嘗試用於初始化/分配std::array變量的文字(沒有雙括號)與那些 arrays 的類型不匹配。 您需要明確地將每個“頂級”元素設為row object,例如:

int main()
{
    struct row {
        double a0;
        double a1;
    };
    
    std::array<row, 2> a = { row{1.0, 2.0}, row{3.0, 4.0} };

    std::array<row, 2> b;
    b = { row{1.0, 2.0}, row{3.0, 4.0} };

    return 0;
}

這是因為,如果沒有雙括號,您的 RHS 文字應該是std::array<row,2> class 的對象(明確)。 但是,使用雙括號,您使用的是聚合初始化而不是(復制)賦值(如您鏈接的帖子中所述)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM