类模板 template

参考网址:http://c.biancheng.net/cpp/biancheng/view/213.html

// demo3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
using namespace std;

template 
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
T test::min()
{
	return (a>b)?b:a;
};

int _tmain(int argc, _TCHAR* argv[])
{
	test  test1(2,3);
	cout< test2(32.12,12.458);
	cout< test3('a','A');
	cout<

 使用类模板的好处就是,可以实现类的成员函数的复用而不用受数据类型的影响。

需要注意的,当把成员函数的实现放在类的外部时,例如上述test类的min()函数,需要加上:

template   //必不可少的
T test::min()    //不要忘记

main函数中定义test类的实例化对象时,也需要注意格式。

转载于:https://www.cnblogs.com/audi-car/p/4391573.html

你可能感兴趣的:(类模板 template)