今天突发奇想,我们平时的++运算符基本都只能自增数字,那我能不能实现一个当用户自增数组时也能完成数组增加一项呢(假设你不会使用c++的变长数组或者vector!)下面就是我的实现方法,各位大佬多多指教哦!比如说gyf大佬和yzs大佬以及lxb大佬?
// 重载++运算符扩容数组
#include <iostream>
class DynamicArray
{
private:
int size;
int *array;
public:
DynamicArray(int size = 1);
void resize(int newSize);
int &operator[](int index);
DynamicArray &operator++()
{
resize(size + 1);
return *this;
}
int getsize(DynamicArray &array);
};
DynamicArray::DynamicArray(int size)
{
this->size = size;
array = new int[size];
}
void DynamicArray::resize(int newSize)
{
int *newArray = new int[newSize];
for (int index = 0; index < newSize; index++)
{
newArray[index] = array[index];
}
delete[] array;
array = newArray;
size = newSize;
}
int &DynamicArray::operator[](int index)
{
return array[index];
}
int DynamicArray::getsize(DynamicArray &array)
{
return array.size;
}
int main()
{
int size = 0;
std::cout << "Please input your size:";
std::cin >> size;
DynamicArray array(size);
for (int index = 0; index < size; index++)
{
std::cin >> array[index];
}
++array;
std::cout << "Please input your " << array.getsize(array) << "-th element:";
std::cin >> array[array.getsize(array) - 1];
for (int index = 0; index < array.getsize(array); index++)
{
std::cout << index + 1 << "-th element:" << array[index] << std::endl;
}
return 0;
}
标签:index,自增,++,运算符,int,DynamicArray,array,size
From: https://blog.csdn.net/yangguanghhh/article/details/136752527