// ============================================================================ // p1c05_11 — 5.7.7 模板类碰到友元函数 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; #include static inline void pause() { printf("按回车键继续..."); (void)getchar(); } // --- 原文片段 [58954472:10] 5.7.7 模板类碰到友元函数 --- #define _CRT_SECURE_NO_WARNINGS #include using namespace std; #include template class Person; //告诉编译器这个函数模板是存在 template void PrintPerson2(Person& p); //友元函数在类内实现 template class Person{ //1. 友元函数在类内实现 friend void PrintPerson(Person& p){ cout << "Name:" << p.mName << " Age:" << p.mAge << endl; } //2.友元函数类外实现 //告诉编译器这个函数模板是存在 friend void PrintPerson2<>(Person& p); //3. 类模板碰到友元函数模板 template friend void PrintPerson(Person& p); public: Person(T1 name, T2 age){ this->mName = name; this->mAge = age; } void showPerson(){ cout << "Name:" << this->mName << " Age:" << this->mAge << endl; } private: T1 mName; T2 mAge; }; void test01() { Person p("Jerry", 20); PrintPerson(p); } // 类模板碰到友元函数 //友元函数类外实现 加上<>空参数列表,告诉编译去匹配函数模板 template void PrintPerson2(Person& p) { cout << "Name2:" << p.mName << " Age2:" << p.mAge << endl; } void test02() { Person p("Jerry", 20); PrintPerson2(p); //不写可以编译通过,写了之后,会找PrintPerson2的普通函数调用,因为写了普通函数PrintPerson2的声明 } int main(){ //test01(); test02(); pause(); return EXIT_SUCCESS; } // --- main ---