在这个例子中,我们将isequal()功能是价值流的一个朋友。isequal()取两个值对象作为参数。因为isequal()是价值类的朋友,它可以访问所有的值对象的私有成员。在这种情况下,它使用的访问在两个对象做一个比较,并返回true,如果他们是平等的。
一个函数可以同时对多个类的一个朋友。例如,考虑下面的例子:
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
|
class
Humidity; class
Temperature { private : int
m_nTemp; public : Temperature( int
nTemp) { m_nTemp = nTemp; } friend
void
PrintWeather(Temperature &cTemperature, Humidity &cHumidity); }; class
Humidity { private : int
m_nHumidity; public : Humidity( int
nHumidity) { m_nHumidity = nHumidity; } friend
void
PrintWeather(Temperature &cTemperature, Humidity &cHumidity); }; void
PrintWeather(Temperature &cTemperature, Humidity &cHumidity) { std::cout
<< "The
temperature is "
<< cTemperature.m_nTemp << "
and the humidity is "
<< cHumidity.m_nHumidity << std::endl; } |
这是一个类的原型,告诉编译器,我们将来要定义一个类称为湿度。没有这条线,编译器会告诉我们他们不知道什么是湿度在分析原型内部温度类printweather()。类的原型的作用相当于函数原型一样——他们告诉编译器事情看上去是什么样子的,可现在和以后的定义。然而,不像函数,类没有返回类型或参数,因此类原型总是简单的类的类名,其中ClassName类的名称。
友元类
它也可能使整个类的朋友,另一个班。这给所有的朋友类可以访问其他类的私有成员,成员。这里有一个例子:
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
|
class
Storage { private : int
m_nValue; double
m_dValue; public : Storage( int
nValue, double
dValue) { m_nValue
= nValue; m_dValue
= dValue; } //
Make the Display class a friend of Storage friend
class
Display; }; class
Display { private : bool
m_bDisplayIntFirst; public : Display( bool
bDisplayIntFirst) { m_bDisplayIntFirst = bDisplayIntFirst; } void
DisplayItem(Storage &cStorage) { if
(m_bDisplayIntFirst) std::cout
<< cStorage.m_nValue << "
"
<< cStorage.m_dValue << std::endl; else
// display double first std::cout
<< cStorage.m_dValue << "
"
<< cStorage.m_nValue << std::endl; } }; |