指针未在类成员函数中修改

Pointer doesn't get modified in class member function

本文关键字:函数 修改 成员 指针      更新时间:2023-10-16

我正在用模板和类制作一个动态数组。

这是我遇到问题的代码:

template<typename GType>
class GArray
{
   GType* array_type = nullptr;
   int size = 0;
public:
GArray(GType Size)
{
    size = Size;
    array_type = new GType[size];
    for (int i = 0; i < size; i++)
        array_type[i] = NULL;
}
void Push(GType Item)
{
    size++;
    GType* temp = new GType[size];
    for (int i = 0; i < size-1; i++)
        temp[i] = array_type[i];
    temp[size] = Item;
    delete[] array_type;
    array_type = temp;
    temp = nullptr;
}
GType& operator[] (int Index)
{
    if (Index >= 0 && Index < size)
        return array_type[Index];
}
};
int main()
{
GArray<int> arr(2);
arr[0] = 10;
arr[1] = 20;
arr.Push(30);

// print array
for (int i = 0; i < arr.Size(); i++)
    cout << arr[i] << endl;
return 0;
}

在main()中,当我打印整个数组值时,最后一个值(应该是30)是一个未定义的值(如-842150451)。

通过几次测试,我可以说在Push()函数内部,array_type指针发生了变化。当我回到main()时,array_type好像没有改变,和以前一样。

错误的原因是

temp[size] = Item

是错误的。它应该被取代

temp[size-1] = Item