类模板在项目开发中的应用
作者:互联网
需求:设计一个数据模板类(MyVector),完成对int、char、Teacher类型元素的管理。
思路:类模板 构造函数 拷贝构造函数 <<运算符重载 []重载 =运算符重载
实现:
MyVector.h:
#include<iostream> using namespace std; template<typename T> class MyVector { friend ostream &operator<< <T> (ostream& out, const MyVector& obj); public: MyVector (int size = 0);//构造函数 MyVector(const MyVector& obj); //拷贝构造函数 ~MyVector();//析构函数 public: T& operator[] (int index); MyVector& operator=(const MyVector& obj); public: int getLen() { return m_len; } protected: T* m_space; int m_len; };
MyVector.cpp
#include<iostream> using namespace std; #include"MyVector.h" template<typename T> ostream& operator<<(ostream& out, const MyVector<T>& obj) { for (int i = 0; i < obj.m_len; i++) { out << obj.m_space[i] << " "; } out << endl; return out; } template<typename T> //MyVector<T> myv1(10); MyVector<T>::MyVector(int size)//构造函数 { m_space = new T(size); m_len = size; } template<typename T> MyVector<T>::MyVector(const MyVector& obj)//拷贝构造函数 { //根据myv1的大小分配内存 m_len = obj.m_len; m_space = new T[m_len]; //copy数据 for (int i = 0; i < m_len; i++) { 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]; } //a3 = a2 = a1; template<typename T> MyVector<T>& MyVector<T>::operator=(const MyVector<T>& obj)//拷贝构造函数 { //先把a2的旧内存释放掉 if (m_space != NULL) { delete[] m_space; m_space = NULL; m_len = 0; } //根据a1分配内存 m_len = obj.m_len; m_space = new T[m_len]; //copy数据 for (int i = 0; i < m_len; i++) { m_space[i] = obj[i]; } return *this;//a2 = a1,返回的是a2的自身 }
test.cpp:
#include<iostream> using namespace std; #include"MyVector.cpp" int main() { MyVector<int> myv1(10); for (int i = 0; i < myv1.getLen(); i++) { myv1[i] = i + 1; cout << myv1[i] << " "; } cout << endl; MyVector<int>myv2 = myv1; for (int i = 0; i < myv2.getLen(); i++) { myv2[i] = i + 1; cout << myv2[i] << " "; } cout << myv2 << endl; system("pause"); return 0; }
标签:MyVector,obj,space,int,len,开发,应用,模板,构造函数 来源: https://www.cnblogs.com/ymj11/p/13747006.html