首先放重点:
容器都是值寓意,而非引用寓意。向容器中放入元素,都是放入元素的拷贝份(上黑马程序员网课的老师处得知)
#include<iostream>
using namespace std;
template<class T>
class MyArray
{
public:
MyArray(int capacity) //构造数组
{
this->mCapacity = capacity;
this->mSize = 0; //数组中不存在元素
//分配内存
this->ptr = new T[this->mCapacity];
}
MyArray(const MyArray& arr) //拷贝构造
{
this->mCapacity = arr.mCapacity;
this->mSize = arr.mSize;
this->ptr = new T[this->mCapacity];
//拷贝数据
for (int i = 0; i < this->mSize; ++i)
{
this->ptr[i] = arr.ptr[i];
}
}
MyArray<T> operator=(const MyArray& arr) //重载等号
{
if (this->ptr != NULL) //数组中有元素就删除
{
delete[] this->ptr;
}
this->mCapacity = arr.mCapacity;
this->mSize = arr.mSize;
this->ptr = new T[this->mCapacity];
//拷贝数据
for (int i = 0; i < this->mSize; ++i)
{
this->ptr[i] = arr.ptr[i];
}
return *this;
}
T& operator[](int index) //数组下标
{
return this->ptr[index];
}
void Pushback(T& data) //插入数组
{
if (this->mSize >= this->mCapacity)
{
cout << "数组已满" << endl;
return;
}
this->ptr[this->mSize] = data;
this->mSize++;
}
void Pushback(T&& data) //加一个取址符可以插入右值
{
if (this->mSize >= this->mCapacity)
{
cout << "数组已满" << endl;
return;
}
this->ptr[this->mSize] = data;
this->mSize++;
}
void Mysort() //正序排列
{
for (int i = 0; i < this->mSize; ++i)
{
for (int j = i + 1; j < this->mSize; ++j)
{
if (this->ptr[i] > this->ptr[j])
{
T temp = ptr[i];
ptr[i] = ptr[j];
ptr[j] = ptr[i];
}
}
}
}
void Myprtintf() //打印数组
{
for (int i = 0; i < this->mSize; ++i)
{
cout << this->ptr[i] << " ";
}
cout << endl;
}
bool Empty() //判断数组是否为空
{
if (this->mSize > 0)
{
cout<<"true";
return true;
}
else
{
cout << "false";
return false;
}
}
~MyArray()
{
if (this->ptr != NULL)
{
delete[] this->ptr;
}
}
public:
int mCapacity; //数组的容量
int mSize; //数组包含元素的个数
T* ptr; //指向数组元素的指针
};
void test01()
{
MyArray<int> arr1(10);
int a = 10;
arr1.Pushback(a);
arr1.Pushback(20);
arr1.Pushback(7);
arr1.Pushback(10);
arr1.Pushback(20);
/*for (int i = 0; i < arr1.mSize; ++i)
{
cout << arr1[i] << " ";
}
cout << endl;*/
arr1.Myprtintf();
arr1.Mysort();
/*for (int i = 0; i < arr1.mSize; ++i)
{
cout << arr1[i] << " ";
}*/
arr1.Myprtintf();
cout << "shan";
arr1.Myprtintf();
}
int main()
{
test01();
return 0;
}
实现数组的简单功能,后期变强后再完善