## 友元

```   1 class point {
2 private:
3     int x, y;
4 public:
5     friend bool isequal(point a, point b); //声明isequal函数是point类的友元函数
6 };
7 bool isequal(point a, point b) {
8     return a.x == b.x && a.y == b.y; //友元函数可以直接访问类的私有成员x和y
9 }
10
11 int main() {
12     point a, b;
13     // initialize
14     cout << isequal(a, b);
15 }
```

```   1 class point {
2 private:
3     int x, y;
4 public:
5     int &get_x() { return x; }
6     int &get_y() { return y; }
7 };
8 bool isequal(Point a, Point b) {
9     return a.get_x() == b.get_x() && a.get_y() == b.get_y();
10 }
11
12 int main() {
13     point a, b;
14     // initialize
15     cout << isequal(a, b);
16 }
```

```   1 class point {
2     int x, y;
3     friend class rectangle; // Rectangle是Point的友元类，Rectangle类的成员函数可以访问Point类的私有成员
4 };
5 class rectangle {
6     point p1, p2;
7 public:
8     void display() {
9         cout << p1.x << p1.y << p2.x << p2.y;
10     }
11     bool in(point p) {
12         return p.x >= p1.x && p.x < p2.x && p.y >= p1.y && p.y < p2.y;
13     }
14 };
15
16 int main() {
17     rectangle rect;
18     // initialize
19     rect.display();
20 }
```

C++:友元 (last edited 2008-03-13 21:00:31 by czk)

ch3n2k.com | Copyright (c) 2004-2022 czk.