簡體   English   中英

c++ 使用構造函數參數在初始化列表中初始化 std::array of std::arrays

[英]c++ initialize std::array of std::arrays in the initializer list using constructor parameters

我有一個這樣的構造函數:

class MyClass {
  protected:
    std::size_t size1;
    std::size_t size2;
    std::array<std::array<std::pair<std::uint64_t, std::uint64_t>>> items;
  public:
    MyClass(): MyClass(1, 1, <???>) {}
    MyClass(std::size_t size1, std::size_t size2): size1(size1), size2(size2), <???> {}
};

我不確定上面的部分是否可以完成:根據size1和size2提供的大小將arrays對的數組初始化為全0。 我用谷歌搜索了一下,但似乎無法找到這方面的代碼示例。 任何幫助,將不勝感激。

正如 Yksisarvinen 提到的, std::array需要在編譯時知道它的大小。 如果需要在運行時設置大小,請改用std::vector 但是,如果您在編譯時確實知道大小,則使MyClass成為模板並將所需的大小作為模板參數傳遞:

template<std::size_t size1 = 1, std::size_t size2 = 1> {
protected:
    std::array<std::array<..., size2>, size1> items{};
public:
    MyClass() = default;
    ...
};

請注意, items聲明后的{}確保所有值都設置為零。 然后你可以像這樣實例化它:

MyClass<3, 5> myObject;

暫無
暫無

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

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