友元类

友元类:把一个类作为另一个类的友元,如果一个类指定了友元类,则友元类的成员函数可以访问此类包括非公有成员在内的所有成员

友元的利弊:友元不是类成员,但是它可以访问类中的私有成员。友元的作用在于提高程序的运行效率,但是,它破坏了类的封装性和隐藏性,使得非成员函数可以访问类的私有成员。不过,类的访问权限确实在某些应用场合显得有些呆板,从而容忍了友元这一特别语法现象。

注意事项:
(1) 友元关系不能被继承
(2) 友元关系是单向的,不具有交换性。若类B是类A的友元,类A不一定是类B的友元,要看在类中是否有相应的声明。
(3) 友元关系不具有传递性。若类B是类A的友元,类C是B的友元,类C不一定是类A的友元,同样要看类中是否有相应的申明

#include "stdafx.h"
#include <iostream>
using namespace std;

#if 0
把PointManagement声明为Point的友元,Point的对象就可以
在PointManagement的类(或者函数)中访问Point的private数据成员
#endif

class Point
{
public:
	Point(double xx, double yy)
		:x(xx), y(yy) {}

	friend class PointManagement; //声明为Point的友元类

private:
	double x, y;
};

class PointManagement
{
public:
	double getDirectDistance(Point &a, Point &b);
	double getTriDistance(Point &a, Point &b);

};

double PointManagement::getDirectDistance(Point &a, Point &b)
{
	double dx = a.x - b.x;
	double dy = a.y - b.y;
	return sqrt(dx*dx + dy*dy); //sqrt 为开平方的函数
}

int _tmain(int argc, _TCHAR* argv[])
{
	Point a(1, 2); Point b(3, 4);

	PointManagement pm;
	double dis = pm.getDirectDistance(a, b);
	cout << dis << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值