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
// friend class
#include <iostream>
using namespace std;
class Square;
class Rectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (Square a);
};
class Square {
friend class Rectangle;
private:
int side;
public:
Square (int a) : side(a) {}
};
void Rectangle::convert (Square a) {
width = a.side;
height = a.side;
}
int main () {
Rectangle rect;
Square sqr (4);
rect.convert(sqr);
cout << rect.area();
return 0;
}
在这个例子中,类矩形类的成员函数的矩形方允许访问方私有的和受保护的成员的一个朋友。更具体地说,矩形访问成员变量平方::侧,它描述了一侧的广场。
还有别的东西在这个新的例子:在程序的开始,有一个空的声明类广场。这是必要的因为类矩形使用方(如成员转换参数),和方使用矩形(宣布它的朋友)。
友谊是没有相应的规定:除非在我们的例子中,矩形被方朋友类,但方不被认为是矩形的一个朋友。因此,长方形的成员函数可以访问受保护的和私有成员方而不是周围的其他方法。当然,如果需要方也被宣布的朋友,矩形,授予该访问。
另一个属性的友谊是不及物动词:一个朋友的朋友是不被认为是朋友,除非明确规定。