#include
using namespace std;
template
class MyArray
{
public:
MyArray(int cap)
{
mCap = cap;
mSize = 0;
arr = new T[sizeof(cap) + 1];//申请空间
};
MyArray(const MyArray& ar) //拷贝构造
{
if (mCap != NULL)
{
delete[]mCap;
}
arr = new T[strlen(ar.mCap) + 1];
mCap = ar.mCap;
mSize = ar.mSize;
};
void PusArry(T &i)//往后插入元素
{
if (mSize >= mCap)
{
return;
}
arr[mSize] = i;
mSize++;
}
void PusArry(T &&i)//解决当插入值为常量的情况
{
if (mSize >= mCap)
{
return;
}
arr[mSize] = i;
mSize++;
}
void printArry()//打印数组
{
for (int i = 0; i < mSize; i++)
{
cout << arr[i] << ends;
}
cout << endl;
}
T& operator[](int i)
{//重载[]运算符
return this->arr[i];
}
friend ostream &operator<<(ostream& out, MyArray
{
for (int i = 0; i < ar.mSize; i++)
{
out << ar.arr[i] << ends;
}
out << endl;
return out;
}
~MyArray()
{
if (arr != NULL)
{
delete[] arr;//释放内存
}
};
private:
int mCap;
int mSize;
T *arr;
};
void test01()
{
MyArray
int a = 1, b = 5;
arr.PusArry(a);//变量
arr.PusArry(b);
arr.PusArry(2);
arr.PusArry(8);//常量
arr.printArry();//打印arr
MyArray
ar.PusArry('a');
ar.PusArry('b');
ar.PusArry('c');
ar.PusArry('d');
ar.PusArry('e');
ar.printArry();//打印ar
cout << ar;//调用重载<<运算符
cout << ar[4] << endl;//通过下标访问//重载[]运算符
}
void main()
{
Test01();
}
运行结果: