数组类型 int[] 不可赋值
Array type int[] is not assignable
我正在使用数组实现 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;
我该如何解决这个问题?
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;
,并实现适当的 copy/move 构造函数和 copy/move赋值运算符,根据 Rule of 3/5/0.
我正在使用数组实现 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;
我该如何解决这个问题?
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;
,并实现适当的 copy/move 构造函数和 copy/move赋值运算符,根据 Rule of 3/5/0.