2013-09-11 38 views
0

我想知道是否有人可以給我例子如何聲明一個二維數組,如果我想使用它作爲類變量。大小也應該是變量。C++二維數組作爲私有類變量

+0

你應該去看看你應該怎麼做,然後回來,並顯示你做了什麼。那麼我們可以幫助您解決您遇到的任何問題! – Aesthete

回答

1

這取決於你所說的「數組」。在C++中,如果在編譯時未知其大小(或大小),則無法聲明內置數組類型的成員。

如果您需要一個具有運行時大小數組結構的數據結構,則必須自己實現它或使用庫實現。在這種情況下,類的直接私有成員不會被聲明爲內置數組類型,而是作爲某種間接引用存儲在動態內存中的實際數組。在最簡單的情況下,您將不得不聲明指針類型的成員。或者,您可以使用std::vector類型的成員,該成員通常將實際的數組數據保存在動態內存中,並在內部存儲指針。

在你的情況,對於一個二維數組可以聲明std::vector<std::vector<T>>類型的成員。

0
class ThisClass { 
private: 
    int** MyArray; 
    int Xlim,Ylim; //Xlim can be used during deletion. May be useful elsewhere. 
public: 
    ThisClass(int x,int y) { 
     Xlim = x; 
     Ylim = y; 
     MyArray = new int*[x]; 
     for(int i = 0; i < x; i++) { 
      MyArray[i] = new int[y]; 
     } 
    } 
    ~ThisClass() { 
     for(int i = (Xlim-1); i >= 0; i--) { 
      delete [] MyArray[i]; 
     } 
     delete [] MyArray; 
    } 
}; 


int main(int argc, char* argv[]) { 

    ThisClass Mine(3,4); 

    return 0; 
} 
+0

爲什麼刪除元素? – giordan12

+0

如果您動態分配內存,則需要將其銷燬。本質上,應用程序在運行時會從系統中獲取內存。如果不摧毀它(還給),那麼你的應用程序水蛭內存(內存泄漏),並最終你的系統運行內存不足,或者你有一個堆棧溢出。至少我怎麼理解它。有人說,聰明的它[這種方式(http://www.inf.udec.cl/~leo/teoX.pdf)。因此,我們添加這些線在你的析構函數,當你的對象超出範圍的內存又釋放回系統。 – Chemistpp

0

大小你沒有明確說明你想要一個可變大小的多維數組(只是你想要大小變量),這裏是一個固定大小的解決方案。

template <typename T, unsigned int WIDTH, unsigned int HEIGHT> 
struct Matrix 
{ 
    Matrix() : width(WIDTH), height(HEIGHT) {} 
    T* operator[](unsigned int idx) { return elements[idx]; } 
    T elements[WIDTH][HEIGHT]; 
    int width, height; 
}; 

class Foo 
{ 
    public: 
     float GetValue(unsigned int x, unsigned int y) 
     { 
      // Now you can access the width and height as variables. 
      assert(x < m_matrix.width && y < m_matrix.height); 

      // Operator allows you to index like so. 
      return m_matrix[x][y]; 
     } 
    private: 
     // A private, 4 by 4 matrix of floats. 
     Matrix<float, 4, 4> m_matrix; 
};