友元函數和友元類
友元函數是可以直接訪問類的私有成員的非成員函數。它是定義在類外的普通函數,它不屬於任何類,但需要在類的定義中加以聲明,聲明時只需在友元的名稱前加上關鍵字friend,其格式如下:friend 類型 函數名(形式參數); 友元函數的聲明可以放在類的私有部分,也可以放在公有部分,它們是沒有區別的,都說明是該類的一個友元函數。(友元在類內定義的位置也是任意的,不管是出現在類的private、pretected或public部分,含義均相同。) 一個函數可以是多個類的友元函數,只需要在各個類中分別聲明。友元函數的調用與一般函數的調用方式和原理一致。
eg1
#include "stdafx.h"
#include <iostream.h>
#include <math.h>
class Point
{
public:
Point(double xx, double yy) { x=xx; y=yy; }
void Getxy();
friend double Distance(Point &a, Point &b);
private:
double x, y;
};
void Point::Getxy()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
double Distance(Point &a, Point &b)
//注意不是double Point::Distance(Point &a, Point &b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx*dx+dy*dy);
}
void main()
{
Point p1(3.0, 4.0), p2(6.0, 8.0);
p1.Getxy();
p2.Getxy();
double d = Distance(p1, p2);
cout <<"Distance is "<<d<<endl;
}
友元類的所有成員函數都是另一個類的友元函數,都可以訪問另一個類中的隱藏信息(包括私有成員和保護成員)。 當希望一個類可以存取另一個類的私有成員時,可以將該類聲明爲另一類的友元類。定義友元類的語句格式如下:friend class 類名;
其中:friend和class是關鍵字,類名必須是程序中的一個已定義過的類。使用友元類時注意:
(1) 友元關係不能被繼承。
(2) 友元關係是單向的,不具有交換性。若類B是類A的友元,類A不一定是類B的友元,要看在類中是否有相應的聲明。
(3) 友元關係不具有傳遞性。若類B是類A的友元,類C是B的友元,類C不一定是類A的友元,同樣要看類中是否有相應的申明
eg2
#include "stdafx.h"
#include <iostream>
//友元的宿主類
class Man
{
friend class Thief; //聲明友元類
public:
Man(): money(100){}; //構造函數,將初始的金錢數設置爲100
void SpendMoney()
{
money --;
}
int ReportMoney()
{
return money;
}
private:
int money;
};
//友元類的定義
class Thief
{
public:
void ThieveMoney(Man& haplessMan)
{
haplessMan.money -= 10;
}
};
int main(int argc, char *argv[])
{
Man man;
man.SpendMoney();
std::cout<<man.ReportMoney()<<std::endl;
Thief thief;
thief.ThieveMoney(man);
std::cout<<man.ReportMoney()<<std::endl;
return 0;
}
嵌套友元
嵌套友元函數 儘管將函數的定義式放在類內部,但它並不是一個成員函數,對於省略受限的定義形式它將成爲一個全局函數::test()
eg3
#include "stdafx.h"
#include <iostream.h>
class A
{
public:
A(int _a) : a(_a) {};
friend void test(A& x)
{
x.a = 100;//定義::test()友元函數
cout<<x.a<<endl;
};
private:
int a;
};
int main(int argc, char *argv[])
{
A a(5);
test(a);
return 0;
}
對於嵌套類,也不能訪問私有成員。嵌套類要訪問私有成員也必須定義爲友元。請看下面 eg4
#define SZ 20
class holder
{
private:
int a[SZ];
public:
void initialize();
class pointer
{
private:
holder *h;
int* p;
public:
void initialize(holder* H);
//move around in the array.
void next();
void previous();
void top();
void end();
//access values.
int read();
void set(int i);
};
friend holder::pointer;
};
類holder包含一個整型數組和一個嵌套類pointer。通過定義pointer爲holder的友元,使得pointer成員可以訪問holder類的私有成員:friend holder : :pointer ;