全局函数与友元
全局函数内实现 --- 直接在类内声明友元即可
全局函数类外实现 --- 需要提前让编译器知道全局函数的存在
#include<iostream>
using namespace std;
#include<string>
//通过全局函数打印person信息
//类外实现
template<class T1, class T2>
class person;
template<class T1,class T2>
void printPerson2(person<T1,T2> &p)
{
cout << "类外实现: " << p.m_Name
<< " " << p.m_Age << endl;
}
template<class T1,class T2>
class person
{
//全局函数作为友元,类内实现
/*friend void printPerson(person<T1 ,T2> p)
{
cout << p.m_Name
<< " " << p.m_Age << endl;
}*/
//全局函数 类外实现
//加空模板的参数列表
//如果全局函数是类外实现的话,需要提前让编译器知道
friend void printPerson2<>(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 test1()
//{
// person<string, int>p1("Tom", 20);
// printPerson(p1);
//}
void test2()
{
person<string, int>p1("Jerry", 21);
printPerson2(p1);
}
int main()
{
test2();
system("pause");
return 0;
}
总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别