友元函数和友元类

来源:互联网 发布:电子商务模式价值网络 编辑:程序博客网 时间:2024/05/16 14:23

 友元关系的定义: 是一种提供了不同类或对象的成员函数之间、类的成员函数与一般函数之间进行数据共享的机制。

解决的问题: 可以通过友元关系,一个普通的函数或者类的成员可以访问封装于另一个类的数据。

友元函数在类中用关键字friend来修饰的非成员函数。

友元函数可以是普通的函数,也可以是其他类中的成员函数,它的函数体中通过对象名访问类的私有和保护成员。

类  point  的对象代表一个平面坐标系中的一个点

例题: 求两个点的距离

解题方法1 利用友元函数

//此为point类的头文件

//“1.h”文件
class Point {
public:Point(int x = 0 , int y = 0) :X(x), Y(y) {}
  friend double dist(Point &p1, Point &p2);
private:
int X, Y;
};


#include"1.h"
#include<cmath>
double dist(Point &p1, Point &p2)
{
double x = p1.X - p2.X;
double y = p1.Y - p2.Y;
return sqrt(x*x + y*y);
}


#include"1.h"
#include<iostream>
using namespace std;
int main()
{
Point dian1(2,3), dian2(5,7);
cout << "the distance is:" ;
cout << dist(dian1, dian2) << endl;
return 0;
}




解题方法2 利用静态函数求解

class Point {
public:Point(int x = 0, int y = 0) :X(x), Y(y) {}
       static double dist( Point m,Point n);                        //静态函数的声明
private:
int X, Y;
};
#include"1.h"
#include<cmath>
 double Point::dist( Point m,Point n)                 //静态函数的定义
{
return sqrt((m.X-n.X)*(m.X-n.X) + (m.Y-n.Y)*(m.Y-n.Y));

#include"1.h"
#include<iostream>
using namespace std;
int main()
{

Point dian1(2, 3),dian2(5,7);
cout << "the distance is:"<<Point::dist(dian1,dian2)<<endl;
return 0;

}



友元类,

若A类是B类的友元类,则A类的所有成员函数都是B类的友元函数,都可以访问B类的私有和保护成员。

class B{

friend class A;

……

}

规则:

1.友元关系是不能传递的,如A是B的友元,C是A的 友元,但是C和B不能进行数据共享;

2.友元关系是单向的,如A是B的友元,A就可以访问B中的成员,但是B不能访问A;

3.友元关系是不能继承的!!!!

原创粉丝点击