14.3 - Template classes
来源:互联网 发布:python账号注册登录 编辑:程序博客网 时间:2024/05/19 21:42
Templates and container classes
首先我们看下面的类
class IntArray{private: int m_nLength; int *m_pnData; public: IntArray() { m_nLength = 0; m_pnData = 0; } IntArray(int nLength) { m_pnData = new int[nLength]; m_nLength = nLength; } ~IntArray() { delete[] m_pnData; } void Erase() { delete[] m_pnData; // We need to make sure we set m_pnData to 0 here, otherwise it will // be left pointing at deallocated memory! m_pnData = 0; m_nLength = 0; } int& operator[](int nIndex) { assert(nIndex >= 0 && nIndex < m_nLength); return m_pnData[nIndex]; } int GetLength() { return m_nLength; }};
使用这个类,我们可以方便的创建整数数组,但是如果我们想要创建double数组,传统的做法需要创建一个全新的类。使用template class则是一个简单高效的新方法。
template <typename T>class Array{private: int m_nLength; T *m_ptData; public: Array() { m_nLength = 0; m_ptData = 0; } Array(int nLength) { m_ptData= new T[nLength]; m_nLength = nLength; } ~Array() { delete[] m_ptData; } void Erase() { delete[] m_ptData; // We need to make sure we set m_pnData to 0 here, otherwise it will // be left pointing at deallocated memory! m_ptData= 0; m_nLength = 0; } T& operator[](int nIndex) { assert(nIndex >= 0 && nIndex < m_nLength); return m_ptData[nIndex]; } // The length of the array is always an integer // It does not depend on the data type of the array int GetLength(); // templated GetLength() function defined below}; template <typename T>int Array<T>::GetLength() { return m_nLength; }
值得注意的是我们在类的外面定义了GetLength()成员函数。这就需要这个函数有自己的template declaration。 而且template array class是Array<T>而不是Array。
下面是个使用上述template class的例子
int main(){ Array<int> anArray(12); Array<double> adArray(12); for (int nCount = 0; nCount < 12; nCount++) { anArray[nCount] = nCount; adArray[nCount] = nCount + 0.5; } for (int nCount = 11; nCount >= 0; nCount----;) std::cout << anArray[nCount] << "\t" << adArray[nCount] << std::endl; return 0;}
和template函数类似,template类也是在调用的时候由编译器实例化。
- 14.3 - Template classes
- C++ Template Classes
- template classes or function
- Template-Based Classes的用法
- C++ template funcitons and classes
- Classes
- 模板类 Template Classes 以及模板类编译时的处理
- template
- Template
- template
- template
- template
- Template
- template
- template
- Template
- template
- Template
- pads pcb中显示/隐藏飞线的方法
- 连接数据库在JTable中显示
- 黑马程序员_银行业务调度系统
- HDU2156(找规律)
- Remove Duplicates from Sorted List II
- 14.3 - Template classes
- Leetcode: Largest Rectangle in Histogram
- Windows进程同步之信号量内核对象(Semaphore)
- MySQL执行计划解读
- 黑马程序员_交通灯管理系统
- Android中Handler类的简单使用,实现图片切换
- 记百度腾讯实习生面试经历-web前端开发
- hibernate配置文件hibernate.cfg.xml的详细解释
- 黑马程序员_java集合类