qfedu-cpp-level/day7/d13.cpp

93 lines
2.0 KiB
C++
Raw Permalink Normal View History

2023-08-01 18:51:53 +08:00
// 类模板的应用
// 设计一个数组模板类(MyArray),完成对不同类型元素的管理
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
template <typename T>
class MyArray
{
private:
int index; // 当前元素的位置
T *arr; // 指向数组的指针
int capacity; // 最大容量
int size; // 当前容量
public:
MyArray(int capacity)
{
this->capacity = capacity; // 最大容量
this->size = 0; // 当前容量为0
this->index = 0; // 当前元素位置为0
this->arr = new T[capacity]; // 申请内存
}
MyArray(const MyArray<T> &other)
{
this->index = other.index; // 当前元素的位置
this->capacity = other.capacity; // 最大容量
this->arr = new T[this->capacity]; // 申请内存
for (int i = 0; i <= this->capacity; i++)
{
this->arr[i] = other.arr[i]; // 拷贝数据
}
this->size = other.size; // 当前容量
}
~MyArray()
{
delete[] this->arr; // 释放内存
}
public:
T &get(int index)
{
return arr[index];
}
T &operator[](int index)
{
return arr[index];
}
// & 是为了链式编程
MyArray<T> &push(T item)
{
if (index < capacity)
{
arr[index++] = item; // 将元素放入数组
size++; // 当前容量加1
}
return *this;
}
T pop()
{
if (index > 0)
{
size--; // 当前容量减1
return arr[--index];
}
else
return NULL;
}
int getSize()
{
return size;
}
};
int main()
{
MyArray<int> a1 = MyArray<int>(20);
a1[0] = 10;
a1[1] = 20;
MyArray<int> a2 = a1;
cout << "a2[0] = " << a2[0] << ", a2[1] = " << a2[1] << endl;
a1.push(30).push(40).push(50);
for (int i = 0; i <= 3; i++)
{
cout << a1.pop() << endl;
}
return 0;
}