友元类

来源:互联网 发布:管理支撑系统大数据 编辑:程序博客网 时间:2024/05/15 06:56

友元类

#include "stdafx.h"#include <iostream>using namespace std;#if 0把一个类作为另一个类的友元,友元类把PointManagement声明为Point的友元,Point的对象就可以在PointManagement的类(或者函数)中访问Point的private数据成员----友元的利弊:友元不是类成员,但是它可以访问类中的私有成员。友元的作用在于提高程序的运行效率,但是,它破坏了类的封装性和隐藏性,使得非成员函数可以访问类的私有成员。不过,类的访问权限确实在某些应用场合显得有些呆板,从而容忍了友元这一特别语法现象。----注意事项(1) 友元关系不能被继承。(2) 友元关系是单向的,不具有交换性。若类 B 是类 A 的友元,类 A 不一定是类 B的友元,要看在类中是否有相应的声明。(3) 友元关系不具有传递性。若类 B 是类 A 的友元,类 C 是 B 的友元,类 C 不一定是类 A 的友元,同样要看类中是否有相应的申明#endifclass 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;}




原创粉丝点击