Posted on 2010-12-06 22:17
Sivan 閱讀(508)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++
看了《金山衛士代碼批評》一文,發現了一些自己存在的問題。
1.const使用
1.1 const修飾參數
1)參數為輸出參數,不論什么數據類型,不論什么參數傳遞方式,都不加const。
2)輸入參數“指針傳遞”,加const防止改動指針。
3)輸入參數“值傳遞”,內置類型,參數不加const修飾,非內置類型,常使用引用傳遞,如果不想改變參數,加const修飾,如void Fun(const A & a)
1.2 const修飾函數返回值
1)返回值“指針傳遞”,加const修飾,函數返回值內容不能被修改,返回值只能賦給加const修飾的同類型指針。
2)返回值“值傳遞”,加const修飾無意義。
3)返回值引用傳遞,一般只出現在類的賦值函數中,實現鏈式表達。
1
class A
2

{
3
A & operator = (const A &other); // 賦值函數
4
}
5
1.3 const成員函數
任何不會修改數據成員的函數都應該聲明為const類型。
規則:
1)const對象只能訪問const成員函數,而非const對象可以訪問任意的成員函數,包括const成員函數。
2)const對象的成員是不可修改的,而const對象通過指針維護的對象卻是可以修改的。
3)const成員函數不可以修改對象的數據,不管對象是否具有const性質。
4)mutable修飾的數據成員,對通過任何手段都可以修改,const成員函數也可以修改。
1
class A
2

{
3
public:
4
A(int i):m_nVal(i)
{m_pVal = new int();}
5
void Print()
{cout<<m_nVal<<" "<<*m_pVal<<endl;}
6
void Print() const
{cout<<"const print:"<<m_nVal<<" "<<*m_pVal<<endl;}
7
int* m_pVal;
8
int m_nVal;
9
};
10
11
int main()
12

{
13
const A a(1);
14
a.Print(); // 規則1,const對象只能防偽const成員函數
15
//a.m_nVal = 2; // 規則2,const對象的成員不可修改
16
*(a.m_pVal) = 3; // 規則2,const對象通過指針維護的對象可以修改
17
return 0;
18
}
19
20
2.表驅動
以前使用過表驅動方法,但是并不知道這就是表驅動。
表驅動方法是一種可以在表中查找信息,而不必使用很多邏輯語句(if,switch case)來找出的方法。
2.1 邏輯性不強
例:
1
void GetWeekDays(string & strDay, int iDay)
2

{
3
if(1 == iDay)
{strDay = "Monday";}
4
else if(2 == iDay)
{strDay = "Tuesday";}
5
else if(3 == iDay)
{strDay = "Wednesday";}
6
else if(4 == iDay)
{strDay = "Thursday";}
7
else if(5 == iDay)
{strDay = "Friday";}
8
else if(6 == iDay)
{strDay = "Saturday";}
9
else if(7 == iDay)
{strDay = "Sunday";}
10
return;
11
}
12
表驅動方法
1
static string strWeekDays[] =
{"Monday","Tuesday","Wednesday",
2
"Thursday","Friday","Saturday","Sunday"};
3
4
void GetWeekDays2(string & strDay, int iDay)
5

{
6
strDay = strWeekDays[iDay-1];
7
}
8
9
2.2 函數指針在表驅動方法中應用
不同分支調用不同的函數
1
void FunA(string strType)
2

{
3
if (strType == "1")
4
{
5
DoFun1();
6
}
7
if (strType == "2")
8
{
9
DoFun1();
10
}
11
if (strType == "3")
12
{
13
DoFun1();
14
}
15
if (strType == "4")
16
{
17
DoFun1();
18
}
19
if (strType == "5")
20
{
21
DoFun1();
22
}
23
if (strType == "6")
24
{
25
DoFun1();
26
}
27
if (strType == "7")
28
{
29
DoFun1();
30
}
31
}
表驅動方法
1
typedef struct
2

{
3
string strType;
4
void (*Fun)(void);
5
}DoTable;
6
7
static const DoTable Table[]=
{
8
{"1",DoFun1},
9
{"2",DoFun2},
10
{"3",DoFun3},
11
{"4",DoFun4},
12
{"5",DoFun5},
13
{"6",DoFun6},
14
{"7",DoFun7}
15
}
16
}
17
18
void FunA(string strType)
19

{
20
int nCount = sizeof(Table)/sizeof(Table[0]);
21
for (int i=0; i!=nCount; ++i)
22
{
23
if (Table[i] == strType)
24
{
25
(*Table[i].Fun)();
26
}
27
}
28
}
參考:
1.http://www.cnblogs.com/Fancyboy2004/archive/2008/12/23/1360810.html
2.http://www.cnblogs.com/MichaelPeng/archive/2010/12/02/1893999.html?page=1#pagedcomment
3.http://baike.baidu.com/view/3707325.htm