类模板小结
模板是 C++类型参数化的多态工具。C++提供函数模板和类模板。
模板定义以模板说明开始。类属参数必须在模板定义中至少出现一次。
同一个类属参数可以用于多个模板。
类属参数可用于函数的参数类型、返回类型和声明函数中的变量。
模板由编译器根据实际数据类型实例化,生成可执行代码。实例化的函数。
模板称为模板函数;实例化的类模板称为模板类。
函数模板可以用多种方式重载。
类模板可以在类层次中使用 。
训练题
1) 请设计一个数组模板类( MyVector ),完成对int、char、Teacher类型元素的管理。
MyVector.h
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class MyVector
{
public:
friend ostream& operator<< <T>(ostream& out, const MyVector& obj);
MyVector(int size = 0); //构造函数
MyVector(const MyVector &obj); //拷贝构造函数
~MyVector(); //析构函数
int GetLen()
{
return m_len;
}
public:
T& operator[](int index);
MyVector& operator=(const MyVector& obj);
private:
T *m_space;
int m_len;
};
MyVector.cpp
#include "MyVector.h"
#include <iostream>
using namespace std;
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>::MyVector(int size = 0) //构造函数
{
m_space = new T[size];
m_len = size;
}
//MyVector<int> myvl2 = myvl;
template <typename T>
MyVector<T>::MyVector(const MyVector &obj) //拷贝构造函数
{
m_len = obj.m_len;
m_space = new T[m_len];
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_len = 0;
m_space = NULL;
}
}
template <typename T>
T& MyVector<T>::operator[](int index)
{
return m_space[index];
}
//a1 = a2
template <typename T>
MyVector<T>& MyVector<T>::operator=(const MyVector& obj)
{
//先把旧内存a1释放掉
if (m_space != NULL)
{
delete[] m_space;
m_space = NULL;
m_len = 0;
}
m_len = obj.m_len;
//再根据a2分配新内存
m_space = new T[m_len];
return *this;
}
MyVector_test.cpp
#include "MyVector.cpp"
#include <iostream>
using namespace std;
void main()
{
MyVector<int> myvl(10);
for (int i = 0; i < myvl.GetLen(); i++)
{
myvl[i] = i + 1;
cout << myvl[i] << " ";
}
cout << endl;
MyVector<int> myvl2 = myvl;
for (int i = 0; i < myvl2.GetLen(); i++)
{
cout << myvl2[i] << " ";
}
cout << endl;
cout << myvl2 << endl;
system("pause");
}
结果: