簡體   English   中英

如何初始化長度為 object 參數的成員數組

[英]How to initialize a member array with a lenght given as object parameter

我無法從傳遞給 object 的參數中確定成員數組的大小。

現在我有這樣的東西,即使不是很方便,它也可以工作:成員數組的大小直接在 class header 中定義。

主.cpp:

int main()
{
    Test foo;
}

類測試.cpp:

Test::Test()
{

}

類測試.h:

class Test
{
    public:
        Test();

    private:
        std::array<int,10> myarray; // I define the size here. 
};

現在我想在創建 object 時將數組大小作為參數傳遞。 像這樣的東西:

主.cpp:

int main()
{
    Test foo(10); // I pass the array size
}

類測試.cpp:

Test::Test(int size): arraysize(size) // I affect the size to a class attribute
{

}

類測試.h:

class Test
{
    public:
        Test(int size);

    private:
        int arraysize;
        std::array<int,arraysize> myarray; // I use the attribute to determine the member array size
};

我嘗試了很多解決方案,但最后總是出現編譯錯誤。 我看到了關於這個主題的其他線程,但他們不允許我找到如何處理這個配置。

我可以使用向量,但在我的情況下,陣列的額外性能非常有益。

數組的大小必須在編譯時知道(換句話說,它是常量)。

要么使用std::vector ,要么在類型中烘焙該大小:

template<int N> // make it a template parameter
class Test
{
    public:
        Test() {}

    private:
        std::array<int, N> myarray;
};

Test<10> test; // array of 10 elements.

就個人而言,我會推薦向量,因為我懷疑性能差異有那么大。

暫無
暫無

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

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