学习C++ primer 之路 - ( 第十四章之 模板类(14.5.2 使用多个类型参数) )

定义多个类型参数的模板

template<class T1,class T2>

定义类;

template<class T1,class T2>
class Pair {
private:
	T1 a;
	T2 b;
public:
	T1 & first();
	T2 & second();
	T1 first() const { return a; }
	T2 second() const { return b; }
	Pair(const T1 & aval, const T2 & bval) :a(aval), b(bval) {}
};
template<class T1, class T2>
T1 & Pair<T1, T2>::first() {
	return a;
}
template<class T1, class T2>
T2 & Pair<T1, T2>::second() {
	return b;
}

在 main函数中使用时:

Pair<string,int>ass("ZHY",1);

注意: 

string->T1 int->T2   然后调用构造函数Pair(const T1 & aval, const T2 & bval) :a(aval), b(bval) {}

猜你喜欢

转载自blog.csdn.net/z1455841095/article/details/82219134