C++---类模板

类模板

类模板定义:
template <class T1,class T2,…>
//可以是class,也可以是typename
class className//利用T1,T2,…
{
//…
}
code(MyPair.h):

template<class T1,class T2>
class MyPair
{
    
    
public:
	MyPair();
	~MyPair();
	MyPair(T1 f,T2 s);	
	
	T1 first;
	T2 second;
};

template<class T1,class T2>
MyPair<T1,T2>::MyPair(){
    
    }

template<class T1,class T2>
MyPair<T1,T2>::MyPair(T1 f,T2 s)
	:first(f),second(s)
{
    
    }

template<class T1,class T2>
MyPair<T1,T2>::~MyPair()
{
    
    }

code(main):

#include "MyPair.h"
#include<iostream>
#include<string>

using namespace std;

class StuStruct
{
    
    
public:
	StuStruct(string s,int a)
		:name(s),age(a){
    
    }
	string name;
	int age;
};

int main(){
    
    
	MyPair<int,string>p1;
	p1.first=1;
	p1.second="zhang";
	cout<<p1.first<<":"
	<<p1.second<<endl;
	
	StuStruct stu1("liu",18);
	MyPair<int,StuStruct>p2(2,stu1);
	cout<<p2.first<<":"
	<<p2.second.name<<":"
	<<p2.second.age<<endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/timelessx_x/article/details/114997824