#include<iostream>
using namespace std;
//掌握类模板配合友元函数的类内和类外实现
//全局函数类内实现-直接在类内声明友元即可
//全局函数类外实现-需要提前让编译器知道全局函数的存在
//1.类外实现先声明模板类的存在
template<class T1, class T2>
class PERSON;
//2.全局函数类外实现
template<class T1, class T2>
void PrintPerson1(PERSON<T1, T2> p)
{
cout << "姓名:" << p.m_Name << endl;
cout << "年龄:" << p.m_Age << endl;
}
template<class T1,class T2>
class PERSON
{
//全局函数类内实现
friend void PrintPerson(PERSON<T1,T2> p)
{
cout << "姓名:" << p.m_Name << endl;
cout << "年龄:" << p.m_Age << endl;
}
//3.全局函数类外实现
//加空模板参数列表
//如果全局函数是类外实现,需要让编译器提前知道这个函数的存在
friend void PrintPerson1<>(PERSON<T1, T2> p);
public:
PERSON(T1 name,T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
private:
T1 m_Name;
T2 m_Age;
};
void test14()
{
//全局函数在类内实现
PERSON<string, int>p("xiansifan",22);
PrintPerson(p);
//全局函数在类外实现
PERSON<string, int>p1("hello", 23);
PrintPerson1(p1);
}
int main()
{
test14();
system("pause");
return 0;
}
网友评论