全局函数类内实现 - 直接在类内声明友元即可(比较简单)
全局函数类外实现 - 需要提前让编译器知道全局函数的存在(复杂了)
1、全局函数类内实现:
#include<iostream> #include<string> using namespace std; template<class T1, class T2> class Person { //1、全局函数配合友元类内实现 friend void ShowPerson(Person<T1, T2>& p)//全局函数访问类内成员,直接写在类内即可 { cout << "姓名:" << p.m_name << " " << "年龄:" << p.m_age << endl; } public: Person(T1 name, T2 age);//默认构造函数声明 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; } int main() { Person<string, int> p("孙悟空", 100); ShowPerson(p); return 0; }
2、全局函数类外实现:
#include<iostream> #include<string> using namespace std; //用到了Person这个数据类型,提前声明 template<class T1, class T2> class Person; //函数的定义要写在类前面,提前让编译器知道,写在类的后边就无法识别了 template<class T1, class T2> void ShowPerson(Person<T1, T2>& p) { cout << "姓名:" << p.m_name << " " << "年龄:" << p.m_age << endl; } template<class T1, class T2> class Person { //1、全局函数配合友元类内实现 //friend void ShowPerson(Person<T1, T2>& p)//全局函数访问类内成员,直接写在类内即可 //{ // cout << "姓名:" << p.m_name << " " << "年龄:" << p.m_age << endl; //} //2、全局函数类内声明,类外实现 friend void ShowPerson<>(Person<T1, T2>& p);//注意加 < > public: Person(T1 name, T2 age);//默认构造函数声明 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; } int main() { Person<string, int> p("孙悟空", 100); ShowPerson(p); return 0; }
总结:
建议全局函数做类内实现,用法简单,而且编译器可以直接识别