簡體   English   中英

在類中定義數組,但大小由構造函數確定

[英]Defining an array in a class but the size is determined in the constructor

我如何將數組定義為類的成員,而數組的大小在其他地方確定,並實際上將其傳遞給構造函數。

更多詳細信息:有一個整數數組,並在類中定義為公共成員。

class foo {
  public:
    int *arr[];
    int s;
};

但是,數組的大小在構造函數中傳遞。

foo::foo()
        : s (array_size)
{
}

這樣做的正確語法是什么?

正確的方法是將STL和std::vector< int >用於此類任務。 以下是可能適合您的粗略概述:

#include <vector>

...

class foo
{
    public:
        std::vector< int > arr_;

        ...

        foo(const int* numbers, int numberCount)
        : arr_(numbers, numbers+numberCount)
        {
        }

        ...

        int size() const
        {
            return arr_.size();
        }

        ...

        int& operator [] (int index)
        {
           return arr_.at(index);
        }
};

有關向量的更多信息,請參見此處 進一步建議:

  • 如果沒有令人信服的理由,請勿將您的實例變量公開。
  • 名稱實例變量有些特殊(例如,通過附加_ )。
  • 許多人不喜歡被全部命名為小寫的類。

您的班級似乎正在嘗試定義“指向int的指針”的數組,而不是您建議的int數組。 然而,經典的答案恰恰是您使用了一個“指向int的指針”,並在構造函數中分配了數組,然后在析構函數中釋放了它。 初步近似:

class foo
{
public:
    int *arr;
    int  s;
    foo(int sz) : s(sz) { arr = new int [s]; }
   ~foo()               { delete [] arr; }
};

如果您打算沿這條路線走,還需要提供一個賦值運算符和一個副本構造函數(正如Mike Seymour提醒我的那樣-謝謝Mike); 如果您不自己編寫,編譯器將為您編寫的默認版本將是錯誤的-極其錯誤。 (SO問題“三個規則是什么?”涵蓋了這一點。)

但是,這(可能)不是異常安全的,因此建議您使用std::vector<int>代替普通指針:

class foo
{
public:
    std::vector<int> arr;
    foo(int sz) : arr(sz) { }
};

您無需顯式存儲大小; 向量為您做到了。

首先,不知道為什么要使用int指針數組,但我是誰來質疑您的設計呢。任何人,都可以使用指針和動態分配來做到這一點。 將數組聲明為...

int **arr;

並在ctor中將其初始化為

*arr = new int*[s];

請記住使用delete[]在dtor上清理它。 另一種選擇是使用std::vector<int*>

也許這並不是您想要的,但是我可以使用模板參數來實現

template<int T>
class Foo
{
    public:
    int array[T];
    int s;
};

您可以像這樣實例化此類

Foo<1024> * f = new Foo<1024> ();
class foo {
   public:
     std::vector m_vec;
     foo(uint32_t size) : m_vec(size) { }
};

暫無
暫無

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

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