c++ 基础知识-模板3
1.类模板成员函数类外实现
类模板函数类外实现
#include <iostream>
#include <string>
using namespace std;
//类模板函数类外实现
template<class T1,class T2>
class Person
{
public:
//构造函数
Person(T1 name,T2 age);
//成员函数
void showInfo();
private:
//成员变量
T1 m_name;
T2 m_age;
};
template<class T1,class T2>
Person<T1,T2>::Person(T1 name,T2 age)
{
this->m_name = name;
this->m_age = age;
}
template<class T1,class T2>
void Person<T1,T2>::showInfo()
{
cout<<"Person()"<<endl;
cout<<this->m_name<<endl;
cout<<this->m_age<<endl;
}
void test()
{
Person<string,int>p("hh",12);
p.showInfo();
//输出
//Person()
// hh
// 12
}
int main()
{
test();
return 0;
}
2.类模板与友元
#include <iostream>
#include <string>
using namespace std;
template<class T1,class T2>
class Person
{
//友元函数,访问类内私有成员
friend void showInfo(Person<T1,T2> &p)
{
cout<<p.m_name<<endl;
cout<<p.m_age<<endl;
}
public:
Person(T1 name,T2 age)
{
this->m_name = name;
this->m_age = age;
}
private:
T1 m_name;
T2 m_age;
};
void test()
{
Person<string,int>p("xiaohu",22);
showInfo(p);
}
int main()
{
test();
return 0;
}