## CSDN博客

### 友元函数和友元类(非模板)

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;

}

(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;
}

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;
}

#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.