友元是c++提供的一种破坏数据封装和数据隐藏特性的机制;
分为友元类和友元函数;
友元函数;
1、由关键字friend 修饰说明的非成员函数;
2、在函数体中可以通过类的对象访问私有成员和protect成员;
作用:增加灵活性,使程序员可以在封装和快速性方面做合理选择。
#include <iostream> #include <cmath> using namespace std; class Point //Point类声明 { public: //外部接口 Point(int xx=0, int yy=0) {X=xx;Y=yy;} int GetX() {return X;} int GetY() {return Y;} friend float Distance(Point &a, Point &b); private: //私有数据成员 int X,Y; }; double Distance( Point& a, Point& b) { double dx=a.X-b.X; double dy=a.Y-b.Y; return sqrt(dx*dx+dy*dy); } int main() { Point p1(3.0, 5.0), p2(4.0, 6.0); double d=Distance(p1, p2); cout<<"The distance is "<<d<<endl; return 0; }
友元类:
1、若一个类为另一个类的友元。则此类的所有成员都能访问对方类的私有成员(即谁是友元,它就可以访问对方类中的所有成员)
#include<iostream> using namespace std; class Date; class Time; class Date { friend class Time; private: int year; int month; int day; public: void setdate(int year,int month,int day) { this->year = year; this->month = month; this->day = day; } void display(); }; void Date::display() { cout<<year<<"."<<month<<"."<<day<<" "; } class Time { Date D2; int hour; int miniter; int second; public: Time(int hour,int miniter,int second); void display() { D2.setdate(2016,12,13); D2.display(); cout<<hour<<":"<<miniter<<":"<<second<<" "; } }; Time::Time(int hour,int miniter,int second) { this->hour = hour; this->miniter = miniter; this->second = second; } int main() { Time T1(11,12,1); T1.display(); }
将一个类中的成员函数声明为另一类的友元:
#include <iostream> using namespace std; class Date; class Time { public: Time(int h,int m,int s):hour(h),minute(m),sec(s){}; void display(Date &); private: int hour; int minute; int sec; }; class Date { public: Date(int h,int m,int s):year(h),month(m),day(s){}; friend void Time::display(Date &); private: int year; int month; int day; }; void Time::display(Date &d) { cout<<d.year<<"/"<<d.month<<"/"<<d.day<<endl; cout<<hour<<":"<<minute<<":"<<sec<<endl; } int main() { Time t1(12,13,52); Date d1(2016,8,3); t1.display(d1); return 0; }