2016-04-24 1 views
1

これを直接作成しようとします。そして、いいえ、私はベクトルを使うことはできません。私はhppのように宣言された既存の配列を持っています:動的配列C++、新しいObj [size]の問題、配列ではなくオブジェクトポインタが1つしか作成されない

Item *itemList[4]; 

次に、オブジェクトポインタの配列の新しいサイズを後で作成する必要があります。 ここで私のサイズ変更配列関数でした。それはスロット1のセットの後でスロットの外に走るので、動作しません。これは、Visual Studioが** tempListを特異オブジェクトへの単数のポインタとして認識するためです。私は何?:あなたが

enter image description here

#ifndef LIST_HPP 
#define LIST_HPP 

#include "Item.hpp" 

class List 
{ 
private:   
    Item *itemList[4]; //Array of 4 Item Object Pointers  
    int numItemsOnList; //Track number of Items on List 
    int numArraySlots; //Track Array Slots available for comparison on addToList 
public: 
    List(); //Default 4 Objects 
    void addToList(string nam, string uni, int numBuy, double uniPrice); 
    void delFromList(string itemName); //Using Name for Lookup 
    void resizeList(int newSize); //Resize new array 
    void printList(); //Print current List 
    double calcTotalPrice(); //Calculate Total Price of items on list 
    bool itemExists(string); 
}; 

#endif 
+0

新しい動的配列を作成する方法は '' std :: vector''を使うことです。なぜあなたはそれを使用していないのですか? –

+0

'itemList2 [0] = itemList [0]'、* itemList2 *は** Itemオブジェクトの**配列です。 * itemList *はItemオブジェクトへのポインタ** **の配列です。 –

+1

ありがとう、しかし、私のコメントを読まなかったのですか?私はベクトルを使用することはできません。ここでは、業界標準やベストプラクティスについては言及していません。この方法を使用する必要がある場合は、これを行う適切な方法が必要です。 –

答えて

0

ポインタ Visual Studioが単数アイテムオブジェクトにtempListがちょうどポインタであると考えていることがわかりますように、このスクリーンショットを追加する

void List::resizeList(int newSiz) { 
Item **tempList = new Item *[newSiz]; 

//Setup tempList 
for (int arraySlot = 0; arraySlot < newSiz; ++arraySlot) 
    tempList[arraySlot] = NULL;  

//Copy List 
for (int listSlot = 0; listSlot < numArraySlots; listSlot++) {    
    tempList[listSlot] = itemList[listSlot];   
} 

delete [] itemList; //Delete Original List 
*itemList = *tempList; //Set new itemList 
} 

をしないのですitemListは静的に作成された配列なので、実行時にサイズを変更することはできません。ダブルポインタItem** itemListを作成し、newを使用してクラスのコンストラクタでその初期サイズを設定し、サイズを変更し、クラスが破棄されたときにそのクラスのdestructorでそのサイズを削除することです。

これを試してみてください:

List::List() 
{ 
    itemList=new Item*[4];//allocate its initial size in the constructor 
} 

List::~List() 
{ 
    delete[] itemList;//release the memory at the destructor 
} 

void List::resizeList(int newSiz) { 
    Item **tempList = new Item *[newSiz]; 

    //Setup tempList 
    for (int arraySlot = 0; arraySlot < newSiz; ++arraySlot) 
     tempList[arraySlot] = NULL;  

    //Copy List 
    for (int listSlot = 0; listSlot < numArraySlots; listSlot++)       
     tempList[listSlot] = itemList[listSlot];   

    delete [] itemList; //Delete Original List 
    itemList = tempList; //Set new itemList 
} 

私はこのことができます願っています。

+0

感謝します!それはそれを得た。以前に宣言された配列が動的配列に変換しようとすると、いくつかの問題があると思います... –

関連する問題