类成员函数可以作为友元在其他类中声明。考虑下面的例子:
// C2248 expected
class B;
class A
... {
int Func1( B& b ) ;
int Func2( B& b ) ;
} ;
class B
... {
private:
int _b;
friend int A::Func1( B& ); // Grant friend access to one,给A类中的Func1函数访问B类的权限。
// function in class B.
} ;
int A::Func1( B & b ) ... { return b._b; } // OK: this is a friend.
int A::Func2( B & b ) ... { return b._b; } // Error: _b is a private member.
在之前的例子当中,只有A::Func1( B& ) 被声明为B类的友元。因此,对私有成员_b的访问在Func1中是正确的,但是在Func2中不正确。
友元类指的是该类中所有的成员函数都是友元函数,也就是说,所有的成员函数都有访问其他类(被声明的类)私有以及保护成员的权限。假设B类中有关于friend的如下声明:
A类中的所有成员函数被赋予了访问B类的权限(友元的权限)。下面是一个友元类的例子:
// compile with: /EHsc
#include < iostream >
using namespace std;
class YourClass
... {
friend class YourOtherClass; // Declare a friend class
public:
YourClass() : topSecret(0)...{}
void printMember() ...{ cout << topSecret << endl; }
private:
int topSecret;
} ;
class YourOtherClass
... {
public:
void change( YourClass& yc, int x )...{yc.topSecret = x;}
} ;
int main() ... {
YourClass yc1;
YourOtherClass yoc1;
yc1.printMember();
yoc1.change( yc1, 5 );
yc1.printMember();
}
这种友元的关系(friendship)是不明确的,除了明确声明的情况下(指在类中写了frined class XXX)。在上面的例子中,YourClass 有访问YourOtherClass的私有成员的权限。
友元的关系不能够被继承,这意味着YourOtherClass 的子类不能够访问YourClass 的私有成员。友元的关系也不能够传递,所以YourOtherClass 的友元不能够访问YourClass 的私有成员。
下面的图中有四个类声明: Base
, Derived
, aFriend
, 和 anotherFriend。在其中只有aFriend 有直接访问Base的私有成员的权限(以及Base从其它类继承来的成员,图中没有表示)。
Implications of friend Relationship
ps:注意不要把声明友元类的位置搞混。类B要在成员函数中操纵类A的成员,需要在类A中写friend class B;