类模板(class template)的友元(friend)和普通类的友元, 有许多区别,
主要原因是类模板包括模板参数(template parameter), 就会导致友元和类模板有许多匹配形式;
主要包括六种形式:
1. 类 – 友元(friend): "模板参数是当前类"的类模板;
2. 类 – 友元: "模板参数任意"的模板类;
3. 模板类 – 友元: "模板参数沟通"的模板类;
4. 模板类 – 友元: "模板参数任意"的模板类
5. 模板类 – 友元: 类;
6. 模板类 – 友元: 当前模板参数(类); (C++11)
详细利用拜见代码及注释,
代码如下:
/* * cppprimer.cpp * * Created on: 2013.11.24 * Author: Caroline */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <string> template <typename T> class Pal; //pal伴侣 class C { friend class Pal<C>; //"以类C实例化"的Pal类, 为C的友元 template <typename T> friend class Pal2; //Pal2类的所有实例化, 都为C的友元 private: void print() { std::cout << "class C" << std::endl; } }; template <typename T> class C2 { friend class Pal<T>; //"与C2类沟通实例化"的Pal类, 为C2的友元 //Pal2类的所有实例化, 都为C2的友元, 留意模板参数(X)不能沟通 template <typename X> friend class Pal2; friend class Pal3; //普通友元 friend T; //C++11 模板范例参数友元 private: void print() { std::cout << "class C2" << std::endl; } }; template <typename T> class Pal { C myC; C2<T> myC2; //必需为T //C2<double> myC2; //实例化差异, 无法利用 public: void printC() { std::cout << "this is class Pal : "; myC.print(); } void printC2() { std::cout << "this is class Pal : "; myC2.print(); } }; template <typename T> class Pal2 { C myC; C2<double> myC2; public: void printC() { std::cout << "this is class Pal2 : "; myC.print(); } void printC2() { std::cout << "this is class Pal2 : "; myC2.print(); } }; class Pal3 { C2<double> myC2; public: void printC2() { std::cout << "this is class Pal3 : "; myC2.print(); } }; class Pal4 { C2<Pal4> myC2; //留意Pal4是C2类的模板参数 public: void printC2() { std::cout << "this is class Pal4 : "; myC2.print(); } }; int main (void) { std::cout << "Hello Mystra!" << std::endl; Pal<C> pc; //Pal类必需实例化为C pc.printC(); //可以利用 //Pal<int> pci; //pci.print(); //报错, 会见了私有成员 Pal2<int> pi2; //Pal2类可以随意实例化 pi2.printC(); Pal<int> pi; //有沟通的示例化, 在类声明C2<T> pi.printC2(); pi2.printC2(); //留意, Pal2类被实例化为<int>, 内部C2类被实例化为<double>; Pal3 p3; p3.printC2(); Pal4 p4; p4.printC2(); return 0; }
输出:
Hello Mystra! this is class Pal : class C this is class Pal2 : class C this is class Pal : class C2 this is class Pal2 : class C2 this is class Pal3 : class C2 this is class Pal4 : class C2
作者:csdn博客 Spike_King