友元函数与友元类

类的友元:

  • 友元是C++提供的一种破坏数据封装和数据隐藏的机制
  • 通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息
  • 为了确保数据的完整性,及数据封装与隐藏的原则,建议尽量不使用或少使用友元
  • 对于友元类,若一个类为另一个类的友元,则此类的所有成员都能访问对方类的私有成员
  • 类的友元关系是单向的


具体看例子:

#include<iostream>
#include<cmath>
using namespace std;
class Point
{
	friend class Line;			//声明Line类是Point类的友元(注意这个是单向的),那么Line对象就可以访问Point里面的私有成员了
	public:	//外部接口
		Point(int x, int y): x(x), y(y) {}
		int Getx() {  return x;  }
		int Gety() {  return y;  }
		friend double Dis1(Point &a, Point &b);
	private:
		int x, y;
};
class Line
{
	public:
		Line(const Point &a, const Point &b): p1(a), p2(a)		//传引用比较快
		{
			double x, y;
			x = a.x-b.x;			//Line可以直接访问Point的私有成员
			y = a.y-b.y;
			len = sqrt(x*x+y*y);
		}
		double Getlen()  {  return len;  }
	private:
		double len;
		Point p1, p2;
};
double Dis1(Point& a, Point& b)		//因为是Point类的友元函数,所以该函数可以直接访问Point内的私有成员
{
	double x, y;
	x = a.x-b.x;
	y = a.y-b.y;
	return sqrt(x*x+y*y);
}
double Dis2(Point& a, Point& b)
{
	double x, y;
	x = a.Getx()-b.Getx();		//Dis2不是友元函数,只能通过调用Point类里的公有函数来获得对象的点坐标值,效率较低
	y = a.Gety()-b.Gety();
	return sqrt(x*x+y*y);
}
int main(void)
{
	Point p1(0,0), p2(3,4);
	Line k(p1, p2);
	cout<<Dis1(p1, p2)<<endl;
	cout<<k.Getlen()<<endl;
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值