类的友元
在一个类中,可以利用关键字friend将其他函数或类声明为友元。
1) 友元函数
友元函数是在类中用关键字friend修饰的非成员函数,虽然不是本类的成员函数,但是可以通过本类的对象来访问该类的私有和保护成员.
如:
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cmath>
class Point{
public:
Point(int xx = 0,int yy = 0){x = xx; y = yy;}
int getx(){return x;}
int gety(){return y;}
friend float fDist(Point &a, Point &b); //友元函数声明
private:
int x,y;
};
float fDist(Point &p1,Point &p2){
double x0 = double(p1.x-p2.x);// 通过友元可以访问该对象的私有数据
double y0 = double(p1.y-p2.y);
return (float)(sqrt(x0*x0+y0*y0));
}
int main(){
Point myp1(1,1),myp2(4,5);
cout << "the distance is:";
cout << fDist(myp1,myp2) << endl;
system("pause");
}
2)友元类
Class B{
……….. // B的成员函数
friend classA; // A是B的友元类
};
若A类是B类的友元类,则A类的所有成员函数都自动成为B类的友元函数,都可以访问B类的私有和保护成员.
举例:
class A{
public:
void display(){cout << x<< endl;}
int getx(){return x;}
friend class B;// B类是A类的友元函数
private:
int x;
};
class B{
public:
void set(int i);
void display();
private:
A a;
};
voidB::set(int i){
i = a.x; // 由于B是A的友元,所以在B的成员函数中可以访问A类对象的私有数据
}
第一, 友元关系是不能传递的(B是A的友元,C是B的友元,那么C不一定是A的友元)
第二, 友元关系是不能继承的
第三, 友元关系是单向的(B是A的友元,B中的函数是A类的友元函数,可以访问A对象的私有和保护数据,但是A中的函数不能访问B中的私有和保护数据)