2016-05-31 22 views
0

我想在一維中將二維數組的大小加倍。我在私有成員私有屬性C++上的動態二維數組

private: 
static const int ARRAY_SIZE=2; 
static const int NUM_ARRAYS=26; 

Profile membersArray[NUM_ARRAYS][ARRAY_SIZE]; 

我希望每當足夠的元素是該行中的ARRAY_SIZE加倍定義的2-d陣列。 在我的私有方法

void MyADT::copyAndDoubleArray(){ 
membersArray= new (nothrow) Profile[NUM_ARRAYS][2*ARRAY_SIZE]; 
} 

下面的錯誤發生在

error: Array type 'Profile[26][2] is not assignable 

我認爲它與陣列是私人屬性做。所以我想我需要知道如何初始化允許動態分配的陣列

+1

您無法調整C++數組的大小。它們的大小在編譯時是固定的。使用'std :: vector'或類似的容器類型。 – PaulMcKenzie

+0

謝謝澄清。它很奇怪,因爲這是一個任務,教授專門聲明我們只允許使用數組。我認爲這是一個練習來展示鏈表的需求。 –

回答

0

不,它沒有任何關係成員聲明爲private,因爲從代碼中可以看出,您試圖訪問內部成員函數membersArray

先保留指向Profile的指針,然後在一個維中分配內存。

Profile *membersArray; 
membersArray = new Profile[NUM_ARRAYS*ARRAY_SIZE]; 

現在您可以訪問的membersArray元素membersArray(x*ARRAY_SIZE+y)其中x and y是二維陣列的尺寸,其中[0 <= x < NUM_ARRAYS] and [0 <= y < ARRAY_SIZE]

現在,如果你想增加現有陣列的大小則:

Profile *temp = new Profile[NUM_ARRAYS*(2*ARRAY_SIZE)]; 
//You can code here to copy existing elements from membersArray to temp. 
//Elements of temp can be accessed as temp(x*(2*ARRAY_SIZE)+y)` where x and y are dimension of the 2D array and [0 <= x < NUM_ARRAYS] and [0 <= y < (2*ARRAY_SIZE)] 
//Now delete membersArray. 
delete [] membersArray; 
//Now assign new increased sized array to membersArray. 
membersArray = temp; 
0

數組類型的對象不能作爲一個整體進行修改:即使它們是「左值」(例如,地址爲o f陣列可以採取),他們不能 出現在賦值運算符的左側。 [*]

所以,你需要使用new[]-expression聲明你的陣列。您可能會得到類似的結果:

private: Profile **ppMembersArray; 
public: constructor() { 
    resize(DEFAULT_ROWS_COUNT, DEFAULT_COLUMNS_COUNT); 
} 
void resize(int newRowsCount, int newColumnsCount) { 
    // allocate some enough memory.. 
    Profile **ppNewMembersArray = new Profile*[newRowsCount]; 
     for (int i = 0; i < newRowsCount; i++) 
      ppNewMembersArray[i] = new int[newColumnsCount]; 
    // copy the existing data to the new address, release the previous ones, and so on.. 
}