資料整理于《大規模C++程序設計》???
???在頭文件的文件作用域中聲明的名稱,可能潛在地與整個系統中任何一個文件的文件作用域名稱沖突。即使在一個.cpp文件的文件作用域中聲明的帶有內部連接的名稱也不能保證一定不與.h文件的作用域名稱沖突。
???主要設計規則:只有類、結構、聯合和自由運算符函數應該在.h文件作用域內聲明;只有類、結構、聯合和內聯函數成員或(內聯)自由運算符應該在.h文件的作用域內定義。
???以下代碼段闡述了上述設計規則。
?1
//
?Driver.h?????????????????????
//
?fine:comment
?2
#ifndef?INCLUDED_DRIVER?????????
//
?fine:internal?include?guard
?3
#define
?INCLUDED_DIRVER
?4
?5
#ifndef?INCLUDED_NIFTY??????????
//
?fine:redundant?include?guard
?6
#include?
"
nifty.h
"
?7
#endif
?8
?9
#define
?PI?3.141592?????????????
//
?Avoid:macro?constant
10
#define
?MIN(X)?((X)<(Y)?(X):(Y))?
//
?Avoid:macro?constant
11
12
class
?ostream;???????????????
//
?fine:?class?dec.
13
struct
?DriverInit;???????????
//
?fine:?class?dec.
14
union?Uaw;???????????????????
//
?fine:?class?dec.
15
16
extern
?
int
?globalVariable;?
//
?Avoid:external?data?dec.
17
static
?
int
?fileScopeVariable;?
//
?Avoid:internal?data?def.
18
const
?
int
?BUFFER_SIZE?
=
?
256
;?
//
?Avoid:const?data?def.
19
enum
?Boolean?
{?zero,?one?}
;??
//
?Avoid:enumeration?at?file?scope
20
typedef?
long
?BigInt;?????????
//
?typedef?at?file?scope
21
22
class
?Driver?
{
23
???
enum
?Color?
{?RED,?GREEN?}
;?
//
?fine:enumeration?in?class?scope
24
???typedef?
int
?(Dirver::
*
PMF)();?
//
?fine:?typedef?in?class?scope
25
???
static
?
int
?s_count;??????
//
?fine:static?member?dec.
26
???
int
?d_size;????
//
?fine:?member?data?def.
27
28
private
:
29
???
struct
?Pnt?
{
30
??????
short
?
int
?d_x,?d_y;
31
??????Pnt(
int
?x,?
int
?y)?
32
???????:?d_x(x),?d_y(y)?
{?}
33
???}
;??????????????
//
?fine:?private?struct?def.
34
???friend?DirverInit;??
//
?fine:?friend?dec.
35
36
public
:
37
???
int
?
static
?round(
double
?d);??
//
?fine:static?member?function?dec.
38
???
void
?setSize(
int
?size);?
//
?fine:?member?function?dec.
39
???
int
?cmp(
const
?Driver
&
)?
const
;?
//
?fine:?const?member?function?dec.
40
}
;???????????????
//
?fine:?class?def.
41
42
static
?
class
?DriverInit?
{
43
??
//
?
44
}
?DriverInit;???
//
?Special?class
45
46
int
?min(
int
?x,?
int
?y);??
//
?Avoid:?free?function?dec.
47
48
inline?
int
?max(
int
?x,?
int
?y)
49
{
50
???
return
?x?
>
?y?
?
?x?:?y;
51??? }
???
//
?Avoid?free?inline?function?def.
52
53
inline?
void
?Driver::setSize(
int
?size)?
54
{
55
???d_size?
=
?size;
56
}
????
//
?fine:?inline?member?function?def.
57
58
ostream
&
?
operator
?
<<
(ostream
&
?o,?
const
?Dirver
&
?d);??
//
?fine:?free?operator?function?def.
59
60
inline?
int
?
operator
?
==
(
const
?Driver
&
?lhs,?
const
?Dirver
&
?rhs)?
61
{
62
???
return
?compare(lhs,?rhs)?
==
?
0
;
63
}
????
//
?fine:?free?inline?operator?func.?def.
64
65
inline?
int
?Driver::round(
double
?d)
66
{
67
???retrun?d?
<
?
0
?
?
?
-
int
(
0.5
?
-
?d)?:?
int
(
0.5
?
+
?d);
68
}
????
//
?fine:?inline?static?member?func.?def.
69
70
#endif
71
72