友元函数和友元类
友元函数是可以直接访问类的私有成员的非成员函数。它是定义在类外的普通函数,它不属于任何类,但需要在类的定义中加以声明,声明时只需在友元的名称前加上关键字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 ;