簡體   English   中英

c ++指針(到一個數組)里面的一個類對象初始化

[英]c++ pointer (to an array) inside of a class object initialization

假設我有一個包含一些結構數組的類,以及一個指向該數組的指針。

struct Box {
    //stuff
};
class Foo {
    private:
        Box *boxPtr     //pointer to an array of Box structs
        int max;        //the size of the partially filled array
        int boxCounter; //the current number of non-NULL elements in the array
    public:
        Foo();                //constructor
        Foo(const Foo &obj);  //copy constructor
        ~Foo();               //destructor
        bool newBoxInsert(Box newBox){
            //adds another Box to my array of Box structs
            boxCounter++;
        }
        //etc
};

在我的int main()中,我不得不創建一個Foo類的全新對象。 我將需要部分填充不確定大小的數組,其指針是boxPtr。

我該如何初始化該數組? 構造函數應該這樣做嗎? 或者我應該讓newBoxInsert處理它?

在任何一種情況下,我將如何實現這一目標? 我猜我必須動態分配數組。 如果是這種情況,那么將指針作為類成員是好的......對嗎?

例如,在將第一個元素添加到我的數組時,我應該使用

boxCounter = 1;
boxPtr = new Box[boxCounter]; 

然后繼續繼續向數組添加元素?

也許這對矢量來說更好。 在添加元素時,它們更加靈活(?)。 向量是否包含結構作為元素?

[/的n00b]

private:
        Box *boxPtr 

將此替換為:

private:
        std::vector<Box> mbox;

它為您節省了所有手動內存管理。 你不太可能出錯。
是的, std::vector可以包含結構作為元素。 實際上它是一個模板類,因此它可以存儲您想要的任何數據類型。

在C ++中如果需要動態數組,最簡單也是最明顯的選擇是std::vector

暫無
暫無

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

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