簡體   English   中英

如何使用給定構造函數的大小初始化 C++ 中的數組?

[英]How can I initialize an array in C++ with a size that is given to the constructor?

我有一個 C++ class 和一個應該是二維數組的成員。 我想將我的數組聲明為 class 的 header 文件中的成員。然后在我的 class 的構造函數中,我想用一個大小(給構造函數)初始化我的數組並用零填充它。

我在 java 中有一個我想要的工作示例:

class Obj {
    int[][] array;
    public Obj(int sizex, int sizey) {
        array = new int[sizex][sizey];
    }
}

public class Main
{
    public static void main(String[] args) {
        Obj o = new Obj(12,20);
    }
}

我不想弄亂指針或 alloc() 和 free()。 因為我的 class 基本上應該是這個數組的包裝器,所以我想保持簡單。

我考慮過使用 std::vector,但由於數組在初始化后從未調整過大小,我覺得 vector 有點過於強大了……有沒有比這更好的方法:?

#include<vector>

class Obj {
    std::vector<std::vector<int>> array;
    public:
    Obj(int xsize, int ysize) {
        std::vector<std::vector<int>> newArray(xsize, std::vector<int>(ysize, 0));
        array = newArray;
    }
};

int main()
{
    Obj o(12,20);
}

std::vector是這里的最佳匹配。 (正如您所說,在大多數情況下,可以避免使用原始 arrays 和指針。另請參閱How can I efficiently select a Standard Library container in C++11?

您可以直接在成員初始化列表中初始化數據成員,而不是在默認初始化后在構造函數體中分配,例如

Obj(int xsize, int ysize) : array(xsize, std::vector<int>(ysize, 0)) {
}

除了使用 std::vector 之外,您只需從堆中分配所需大小的 memory。

class Obj {
    int** arr;
    int x, y;
public:
    Obj(int sizex, int sizey) : x(sizex), y(sizey) {
        arr = new int*[sizex];
        for (unsigned i = 0; i < sizex; i++) {
            arr[i] = new int[sizey];
        }
    }

    //IMPORTANT TO DELETE, OTHERWISE YOU'LL GET A MEMORY LEAK
    ~Obj() {
        for (unsigned i = 0; i < x; i++) {
            delete[] arr[i];
        }
        delete[] arr;
    }
}

暫無
暫無

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

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