动态数组C ++,新Obj [size]仅创建1个对象指针而不是数组的麻烦

jp-tech

我将尽力使这一点变得直接。不,我不能使用向量。我有一个在hpp中这样声明的现有数组:

Item *itemList[4];

然后,我需要稍后创建对象指针数组的新大小。这是我的大小调整数组函数。它不起作用,因为在设置了插槽1之后,它用完了插槽。这是因为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
}

添加此屏幕快照,以便您可以看到Visual Studio认为tempList只是指向单个项目对象指针的指针

在此处输入图片说明

#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
比鲁克·安倍(Biruk Abebe)

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
}

我希望这有帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章