類成員函數可以作爲友元在其他類中聲明。考慮下面的例子:
// 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;