指针未在类成员函数中修改
Pointer doesn't get modified in class member function
我正在用模板和类制作一个动态数组。
这是我遇到问题的代码:
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
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何从子成员函数修改父公共成员变量
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- C++ 使用同一函数时如何修改间距
- C++:通过函数修改数组
- 如何调试指针参数是否通过函数修改
- 为什么我可以在C 11中使用const函数修改类
- Qt - 使用λ函数修改先前连接信号的插槽参数
- 如何返回通过memcpy函数修改的两个阵列
- Arduino esp8266中的c++函数修改了c文件中生成的浮点值,在c++函数退出后,c文件中会出现胡言乱语
- 调用带有扭曲的库函数-修改其某些行为
- 二维数组被函数修改后如何删除
- 由算术运算符成员函数修改的动态数组的复制构造函数
- 如何在函数修改堆栈时将堆栈传递给函数
- 当我们可以使用普通函数修改静态数据成员时,静态成员函数的需求是什么?
- 通过函数修改数组的元素
- 挂钩(热补丁)类成员函数.修改虚函数表项
- 为什么引用成员可以被const成员函数修改
- 使用 friend 关键字和使用成员函数修改类内部的私有变量有什么区别
- c++通过一个函数修改多个数组