一,引入友元类的目的ios
为了在其余类中访问一个类的私有成员在定义类的时候使用关键词friend定义友元函数或是友元类。函数
二,友元类的实现spa
1.友元函数设计
(1).普通函数对类的局限性调试
类的私有成员只能被类的成员访问,若是须要函数须要访问多个类,类的成员函数便很难实现。code
例如计算创建一个point类表示一个点若是想计算两个点的距离,若是使用成员函数难以有效的代表两者的关系,须要一个函数联系两个不一样的类时,通常函数难以知足需求。blog
(2).友元函数的实现ci
#include <iostream> #include <math.h> using namespace std; class point { public: void set(); void showdata(); friend int distance(point &a,point &b); private: int x; int y; }; int distance(point &a,point &b) { int way; way=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); return way; } void point::showdata() { cout<<"x="<<x<<endl; cout<<"y="<<y<<endl; } void point::set() { cout<<"输入x的值"<<endl; cin>>x; cout<<"输入Y的值"<<endl; cin>>y; } int main() { point use_1,use_2; use_1.set(); use_2.set(); use_1.showdata(); use_2.showdata(); cout<<"两点之间的距离为"<<distance(use_1,use_2)<<endl; }
在调试过程当中只要输入两点的x,y值就能计算出两点之间的距离,函数distance()可以访问到point类中的私有数据,由于在定义point是distance在其中被定义为了友元类函数。io
2.友元类class
(1).友元类的实现
#include <iostream> using namespace std; class birth { public: void set(); friend class people; private: int year; int mon; int day; }; class people { public: void set(); void show(birth &a); friend class birth; private: char name; }; void people::show(birth &a) { cout<<name<<endl; cout<<a.year<<endl; cout<<a.mon<<endl; cout<<a.day<<endl; } void people::set() { cin>>name; } void birth::set() { cin>>year; cin>>mon; cin>>day; } int main() { people a; birth b; a.set(); b.set(); a.show(b); }
(2).友元类的单向性
#include <iostream> using namespace std; class birth { public: void set(); private: int year; int mon; int day; }; class people { public: void set(); void show(birth &a); friend class birth; private: char name; }; void people::show(birth &a) { cout<<name<<endl; cout<<a.year<<endl; cout<<a.mon<<endl; cout<<a.day<<endl; } void people::set() { cin>>name; } void birth::set() { cin>>year; cin>>mon; cin>>day; } int main() { people a; birth b; a.set(); b.set(); a.show(b); }
如例所示,将birth类中的friend class people 该函数便不能正常运行。要想实现相互访问只能在两个类中同时定义友元类。
(3).友元类的不可传递性
不一样与a=b,b=c,a=c;若是A是B的友元类,B是C的友元类那么A不是C的友元类。
三,实验设计
利用友元类完成一个员工资料统计系统,可以打印出员工的我的信息与公司信息,其中我的信息是公司信息的友元类。要求这两个类的私有成员在一个函数中赋值,并使用友元函数打印信息。