扩展的friend语法

在C++ 11中,声明一个类为另外一个类的友元时,不再需要使用class关键字,也可以使用typedef(或者using)定义的别名。

 1 class Poly;
 2 typedef Poly P;
 3 
 4 class LiLei {
 5     friend class Poly;    // C++98通过, C++11通过
 6 };
 7 
 8 class Jim {
 9     friend Poly;    // C++98不通过, C++11通过
10 };
11 
12 class HanMeiMei {
13     friend P;    // C++98不通过, C++11通过
14 };

从以上代码中或许看不出来有什么优越性,但是用于模板类的时候,优越感立马就能显现。

1 class P;
2 
3 template <typename T> class Pepope {
4     friend T;    
5 };
6 
7 Pepole<P> pp;    //类型P在这里是People类型的友元
8 Pepole<int> pi; //对于int等内置类型,友元声明被忽略
原文地址:https://www.cnblogs.com/lniwn/p/3387337.html