类的友元

/*类的友元
友元关系提供了不同类或对象的成员函数之间、类的成员函数与一般函数之间进行数据共享的机制

*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class 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修饰的非成员函数,声明的友元函数可以访问的类的私有和保护成员;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#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类对象的私有成员;
}
Fork me on GitHub