类模板 template<class T>
2015-04-04 09:06
417 查看
参考网址:http://c.biancheng.net/cpp/biancheng/view/213.html
使用类模板的好处就是,可以实现类的成员函数的复用而不用受数据类型的影响。
需要注意的,当把成员函数的实现放在类的外部时,例如上述test类的min()函数,需要加上:
template<class T> //必不可少的
T test<T>::min() //不要忘记<T>
main函数中定义test类的实例化对象时,也需要注意格式。
// demo3.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; template <class T> class test { private: T a,b; public: test(T m,T n) { a=m; b=n; } T max() { return (a>b)?a:b; } T min(); }; template<class T> T test<T>::min() { return (a>b)?b:a; }; int _tmain(int argc, _TCHAR* argv[]) { test <int> test1(2,3); cout<<test1.max()<<endl; cout<<test1.min()<<endl; test<float> test2(32.12,12.458); cout<<test2.max()<<endl; cout<<test2.min()<<endl; test<char> test3('a','A'); cout<<test3.max()<<endl; cout<<test3.min()<<endl; return 0; }
使用类模板的好处就是,可以实现类的成员函数的复用而不用受数据类型的影响。
需要注意的,当把成员函数的实现放在类的外部时,例如上述test类的min()函数,需要加上:
template<class T> //必不可少的
T test<T>::min() //不要忘记<T>
main函数中定义test类的实例化对象时,也需要注意格式。
相关文章推荐
- 模板 使用中注意的问题 template<class T>
- C++类模板 template <class T>
- C++类模板 template <class T>
- 模板声明中template <typename T>和template <class T>
- c++中的 template<class Type>
- C++类模板 template <class T>
- 宏和template<class T>
- template<class T>
- SeqStack(Template<class T>)实现
- template<class T>函数模板
- template<class T>函数模板
- template<class T>
- 01模板 使用template<class T>
- template<class T>
- C/C++学习笔记(2)--函数模板template<typename T>,类模板详解(1)
- C++类模板 template <class T>
- c++ 模板<template class T> c++ 模板<template class T>
- template<class T>
- template<class T>函数模板
- UE4 C++类模板 template <class T>