s->mSize = arr.mSize;
p = new T[arr.mCapacity];
for (int i = 0; i < this->mSize; i++)
{
p[i] = arr.p[i];
}
}
//赋值函数
MyArray& operator=(const MyArray& arr)
{
if (this->p != NULL)
{
delete[] this->p;
this->p = NULL;
}
p = new T[arr.mCapacity];
this->mSize = arr.mSize;
this->mCapacity = arr.mCapacity;
for (int i = 0; i < this->mSize; i++)
{
p[i] = arr.p[i];
}
return *this;
}
//重载[]
T& operator[](int index)
{
return this->p[index];
}
//尾插
void Push_Back(const T& val)
{
if (this->mSize == this->mCapacity)
{
return;
}
this->p[this->mSize] = val;
this->mSize++;
}
//尾删
void Pop_Back()
{
if (this->mSize == 0)
{
return;
}
this->mSize--;
}
//析构
~MyArray()
{
if (this->p != NULL)
{
delete[] p;
p = NULL;
}
cout << "析构函数" << endl;
}
int getSize()
{
return this->mSize;
}
private:
T* p;
int mCapacity;
int mSize;
};
类模板实现数组.cpp
点击查看代码
#define _CRT_SECURE_NO_WARNINGS
#include<string>
#include<iostream>
using namespace std;
#include"MyArray.hpp"
class Maker
{
public:
Maker()
{
cout << "无参构造" << endl;
}
Maker(string name,int age)
{
this->name = name;
this->age = age;
}
public:
string name;
int age;
};
void printMaker(MyArray<Maker>& arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << "姓名:" << arr[i].name << " 年龄:" << arr[i].age << endl;
}
}
void test()
{
//Maker类型
MyArray<Maker>myarr(4);
Maker m1("小明", 18);
Maker m2("小强", 19);
Maker m3("小栋", 20);
Maker m4("小兴", 21);
myarr.Push_Back(m1);
myarr.Push_Back(m2);
myarr.Push_Back(m3);
myarr.Push_Back(m4);
printMaker(myarr);
//int类型
MyArray<int>myint(10);
for (int i = 0; i < 10; i++)
{
myint.Push_Back(i + 1);
}
for (int i = 0; i < 10; i++)
{
cout << myint[i] << " " << endl;
}
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}
总结
模板是一个比较重要的概念,是创建泛型类或函数的蓝图或公式。库容器,比如迭代器和算法,都是泛型编程的例子,它们都使用了模板的概念。
-学习C++任重而道远,本人愚钝,唯有勤加练习方能查漏补缺。