【问题标题】:Array type int[] is not assignable数组类型 int[] 不可赋值
【发布时间】:2021-02-25 21:23:38
【问题描述】:

我正在使用数组实现 ADT 堆栈。当堆栈已满时,我想将数组的大小增加一倍。

const int MAX_SIZE = 6 // max size of array stack
template<class ItemType>
class ArrayStack: public StackInterface<ItemType>{
private:
    ItemType items[MAX_SIZE]; // Array of stack items
    int top; // index of top
    int itemCount; // Amount of items in stack
    int maxsize;

这是我的推送方法:

template<class ItemType>
bool ArrayStack<ItemType>::push(const ItemType& newEntry){
    if(itemCount == maxsize){ // resize array
        cout << "resizing an array..." << endl; // just for testing
        ItemType* oldArray = items; // old array to be deleted
        ItemType* newItems = new ItemType[2*maxsize];

        for(int i=0; i<maxsize; i++){
            newItems[i] = oldArray[i]; // copying all array items
        }
        delete[] oldArray; // deallocate
        maxsize = maxsize * 2; // doubling max size
        items = newItems; <- I'm getting error from this code
    } // end if

    // Stack is not full
    top++;
    items[top] = newEntry;
    itemCount++;
    return true;
}

我在尝试将数组大小加倍时遇到此错误:

error: array type 'int [6]' is not assignable
items = newItems;

我该如何解决这个问题?

【问题讨论】:

  • 您是否有理由手动管理动态数组而不是使用std::vector?甚至,你为什么不使用std::stack 开始?
  • 实际上我正在学习“数据抽象和用 C++ 解决问题”,我在第 7 章,他们创建了这样的数组堆栈类,并在“堆栈变满时将数组加倍”正如我在代码中指出的那样,他们确实将数组加倍
  • 不能改变fixed数组的大小,只能分配一个新的dynamic数组并维护一个指针 给它。
  • @RemyLebeau 我绝对同意你的观点,这就是为什么我在这里问这个问题,因为当我在书中看到问题的答案时它没有意义
  • 如果书籍显示一个指针被分配给一个数组,那么这本书是错误的。

标签: c++ arrays stack


【解决方案1】:

ItemType items[MAX_SIZE]; 是一个固定数组。你不能调整它的大小,你不能重新分配它,你当然不能给它分配一个ItemType*指针。

对于您尝试执行的操作,items 需要是 ItemType* 指针而不是 ItemType[] 数组:

template<class ItemType>
class ArrayStack: public StackInterface<ItemType>{
private:
    ItemType *items; // Array of stack items
    ...
};

不要忘记在构造函数中初始化items,并在析构函数中调用delete[] items;,并根据Rule of 3/5/0 实现正确的复制/移动构造函数和复制/移动赋值运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2015-03-08
    相关资源
    最近更新 更多