类模板实现一个支持各种类型的数组
类模板中成员函数创建时机
类模板中成员函数和普通类中成员函数创建时机是有区别的:
普通类中的成员函数一开始就可以创建
类模板中的成员函数在调用时才创建
所以成员函数类外实现的时候,一般不分开写
类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:
解决方式1:直接包含.cpp源文件
解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){};
Person(string n,int ag){
this->name=n;
this->age=ag;
}
private:
string name;
int age;
};
template <class T>
class MyArray{
public:
MyArray(int cap){
this->capacity=cap;
// this->size=siz;
this->Address=new T[this->capacity];
}
MyArray(const MyArray &p){
// if (this->Address!=NULL){
// delete []Address;
// this->capacity=0;
// this->size=0;
// } 这个地方不用写初始化,因为已经在初始化了 hhh
this->capacity=p.capacity;
this->size=p.size;
this->Address =new T[this->capacity];
for (int i=0;i<this->size;i++){
this->Address[i]=p.Address[i];
}
}
//重载复制操作=,做深拷贝
MyArray& operator=(const MyArray &p)
{
if (this->Address!=NULL)
{
delete []Address;
this->capacity=0;
this->size=0;
}
this->capacity=p.capacity;
this->size=p.size;
this->Address =new T[this->capacity];
for (int i=0;i<this->size;i++)
{
this->Address[i]=p.Address[i];
}
return *this;
}
T& operator[](int index)
{
return this->Address[index];
}
void Insert(const T& val )
{
if(this->capacity==this->size)
{
return;
}
this->Address[this->size]=val;
this->size++;
}
void Delete()
{
if(this->size==0)
{
return;
}
this->size--;
}
int getCapacity()
{
return this->capacity;
}
int getSize()
{
return this->size;
}
~MyArray()
{
if(this->Address!=NULL)
{
delete this->Address;
this->Address=NULL;
this->capacity=0;
this->size=0;
}
}
private:
int capacity;
int size;
T *Address ;
};
int main() {
MyArray<Person> p(10);
Person a("z",18);
Person b("l",19);
MyArray<Person> c=p;
cout <<c.getCapacity();
return 0;
}