类的友元 发表于 2017-09-27 | 分类于 C++ /*类的友元友元关系提供了不同类或对象的成员函数之间、类的成员函数与一般函数之间进行数据共享的机制 */ 1234567891011121314151617181920212223242526272829303132333435363738394041424344class A{public: void display(){cout<<x<<endl;} int getX(){return x;}private: int x;};class B{public: void set(int i); void display();private: A a;};``` /*这是类组合的情况,类B中内嵌了类A的对象,但是B的成员函数却无法直接访问A的私有成员x。友元函数是在类中用关键字friend修饰的非成员函数*/``` bash class point{public: point(int x=0,int y=0):x(x),y(y){} friend float dist(point &p1,point &p2); //友元函数声明private: int x,y;};float dist(point &p1,point &p2){ double x=p1.x-p2.x; double y=p1.y-p2.y; return static_cast<float>(sqrt(x*x+y*y));} 友元函数友元函数是在类中用关键词friend修饰的非成员函数,声明的友元函数可以访问的类的私有和保护成员; 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#include <iostream>#include <cmath>using namespace std;class point{public: point(int x=0,int y=0):x(x),y(y){} /* int getX(){return x;} int getY(){return y;}*/ friend float dist(point &p1,point &p2);private: int x,y;};float dist(point &p1,point &p2){ double x=p1.x-p2.x; double y=p1.y-p2.y; return static_cast<float>(sqrt(x*x+y*y));}int main(){ point myp1(1,1),myp2(4,5); cout<<"The distance is:"; cout<<dist(myp1,myp2)<<endl; return 0;}``` ### 友元类若A类为B类的友元类, 则A类的所有成员函数都是B类的友元类,都可以访问B类的私有和保护成员*/class B{……………… //B类的成员声明friend class A; //声明A为B的友元类………………};源程序:``` bash class A{public: void display(){count<<x<<endl;} itn getX(){return x;} friend class B; //B类是A 类的友元类;private: int x;};class B{public: void set(int i); void display();private: A a;};void B::set(int i){ a.x=i; //由于B是A 的友元,所以在B的成员函数中可以访问A类对象的私有成员;}