1.template <class 虚拟类型参数名>
2.用类模板定义对象形式:
- 类模板名 <实际类型名> 对象名;
- 类模板名 <实际类型名> 对象名(实参表);
#include<iostream> using namespace std; template <class numtype> class Compare { public: Compare(numtype a, numtype b) { x = a; y = b; } numtype max() { return (x > y) ? x : y; } numtype min() { return (x < y) ? x : y; } private: numtype x, y; }; int main() { Compare<int> cmp1(3, 7);//cmp1为对象 cout << cmp1.max() << " " << cmp1.min() << endl; Compare<float> cmp2(45.78, 93.6); cout << cmp2.max() << " " << cmp2.min() << endl; system("pause"); return 0; }