所有的类,我们已经写到目前为止已经足够简单,我们已经能够实现的功能,直接在类本身的定义。例如,我们无处不在的日期类:
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
|
class
Date { private : int
m_nMonth; int
m_nDay; int
m_nYear; Date()
{ } //
private default constructor public : Date( int
nMonth, int
nDay, int
nYear) { SetDate(nMonth,
nDay, nYear); } void
SetDate( int
nMonth, int
nDay, int
nYear) { m_nMonth
= nMonth; m_nDay
= nDay; m_nYear
= nYear; } int
GetMonth() { return
m_nMonth; } int
GetDay() { return
m_nDay; } int
GetYear() { return
m_nYear; } }; |
然而,作为类得到更长和更复杂的,混合的定义和实现细节,使课堂更难管理工作。通常情况下,当您在一个类的定义(一个已经编写的类),你不在乎是如何实现的-你想知道如何使用类,只涉及它的定义。在这种情况下,所有的实现细节刚刚获得的方式。
幸运的是,C + +提供了一种单独的定义类的部分实现部分。这是由类定义之外定义的类的成员函数所做的。这样做,只是定义类的成员函数,就像他们的正常功能,但前缀类名称的函数使用作用域操作符(::)(同一个命名空间)。
这是我们的日期和日期类构造函数和setdate()函数的定义类的外部定义。请注意,这些函数的原型,还存在于类定义,但实际执行已经离开了:
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
Date { private : int
m_nMonth; int
m_nDay; int
m_nYear; Date()
{ } //
private default constructor public : Date( int
nMonth, int
nDay, int
nYear); void
SetDate( int
nMonth, int
nDay, int
nYear); int
GetMonth() { return
m_nMonth; } int
GetDay() { return
m_nDay; } int
GetYear() { return
m_nYear; } }; //
Date constructor Date::Date( int
nMonth, int
nDay, int
nYear) { SetDate(nMonth,
nDay, nYear); } //
Date member function void
Date::SetDate( int
nMonth, int
nDay, int
nYear) { m_nMonth
= nMonth; m_nDay
= nDay; m_nYear
= nYear; } |