数组模板类

分析需求

  1. 类模板
  2. 构造函数
  3. 拷贝构造函数
  4. 重载<<和[]和=操作符

1.cpp文件中所包含的代码


#include
using namespace std;
#include"2.h"

 template <typename T>
MyVector<T>::MyVector(int size)
{
	 this->m_space = new T[size];
	 this->m_len=size;
}
template <typename T>
MyVector<T>::MyVector(const MyVector &obj)
{
	 this->m_len = obj.m_len;
 	this->m_space = new T[m_len];
	 for(int i=0;i<m_len;i++)
	 {
  		this->m_space[i] = obj.m_space[i];
	 }
}
template <typename T>
MyVector<T>::~MyVector()
{
 	if(m_space!=NULL)
	 {
 	 delete []m_space;
 	 m_space = NULL;
 	 m_len = 0;
	 }
}
template <typename T>
T& MyVector<T>::operator[](int index)
{
	 return m_space[index];
}
template <typename T>
MyVector<T>& MyVector<T>::operator=(const MyVector &obj)
{
 //先把旧的内存释放掉
	 if(m_space!=NULL)
 	{
  		delete []m_space;
  		m_space = NULL;
 		 m_len = 0;
	 }
	 this->m_len = obj.m_len;
	 this->m_space = new T[m_len];
 	for(int i=0;i<m_len;i++)
 	{
  		this->m_space[i] = obj.m_space[i];
 	}
 	return *this;
}
template <typename T>
int MyVector<T>::getlen()
{
 	return m_len;
}
template <typename T>
ostream& operator<<  (ostream &out,MyVector<T> &obj)
{
	 for(int i=0;i<obj.getlen();i++)
 	{
		out<<obj[i]<<" ";
	 }
 	out<<endl;
	 return out;
}

2.h文件中所包含的代码

#include
using namespace std;
template <typename T>
class MyVector
{
public:
 	MyVector(int size = 0);//构造函数
	 MyVector(const MyVector &obj);//拷贝函数
 	~MyVector();//析构函数
 	int getlen();
 	T& operator[](int index);
 	MyVector& operator=(const MyVector &obj);
 	friend ostream& operator<< <T> (ostream &out,MyVector &obj);
protected:
 	T *m_space;
 	int m_len;
 };
 	

结论

  1. 如果把Teacher类放到MyVector数组中,且Teacher类中含有指针就会出现深拷贝和浅拷贝的问题。
  2. 需要Teacher封装的函数有:
    1. 重写拷贝构造函数
    2. 重写等号操作符
    3. 重写左移操作符

你可能感兴趣的:(数组模板类)