1. 關(guān)于常量引用正像在C語(yǔ)言中使用指針一樣,C++中通常使用引用 有一個(gè)函數(shù)... foo()并且這個(gè)函數(shù)返回一個(gè)引用...... & foo()...., 一個(gè)指向位圖(Bitmap)的引用 ...Bitmap & foo().... 并且這個(gè)位圖(bitmap)是常量const Bitmap & foo ()當(dāng)然你也可以用指針來(lái)做同樣的事情:const Bitmap * foo()foo 返回一個(gè)指針 ... 指向一個(gè)Bitmap ... 并有這個(gè)Bitmap是個(gè)常量.Bitmap * const foo()foo 返回某個(gè)東西,這個(gè)東西是常量 ... 這個(gè)東西又是指針 ... 一個(gè)指向Bitmap的指針.const Bitmap * const foo()foo 返回某個(gè)東西,這個(gè)東西是常量 ... 這個(gè)東西又是指針 ... 一個(gè)指向Bitmap的指針.....并且這個(gè)Bitmap也是常量.指針常量與常量指針請(qǐng)參考Blog: http://www.cnblogs.com/JCSU/articles/1019219.htmlconst總是針對(duì)它左邊的東西起作用, 唯一例外的是,如果const是一個(gè)最左邊的標(biāo)識(shí)符,那么const將針對(duì)它右邊的東西起作用,因些 const int i; 與 int const i; 意思是相同的.原文請(qǐng)參考: http://www.thescripts.com/forum/thread63796.html2. 常量函數(shù)、常量引用參數(shù)、常量引用返回值例1:bool verifyObjectCorrectness(const myObj &obj); //const reference parameter例2:void Add(const int &arg) const; //const function例3:IStack const & GetStack() const { return _stack; } //return const reference常量引用參數(shù)本例中,一個(gè)myObj類型的對(duì)象obj通過(guò)引用傳入函數(shù)verifyObjectCorrectness。為安全起見,使用了const關(guān)鍵字來(lái)確保函數(shù)verifyObjectCorrectness不會(huì)改變對(duì)象obj所引用的對(duì)象的狀態(tài)。此外,通過(guò)聲明參數(shù)常量,函數(shù)的使用者可以確保他們的對(duì)象不會(huì)被改變,也不必?fù)?dān)心在調(diào)用函數(shù)時(shí)帶來(lái)副作用。以下代碼試圖對(duì)聲明為常量引用的形參進(jìn)行修改,從而不會(huì)通過(guò)編譯!
常量函數(shù)1. 一個(gè)函數(shù)通過(guò)在其后面加關(guān)鍵字const,它將被聲明為常量函數(shù)2. 在C++,只有將成員函數(shù)聲明為常量函數(shù)才有意義。帶有const作后綴的常量成員函數(shù)又被稱為視察者(inspector),沒(méi) 有const作后綴的非常量成員函數(shù)被稱為變異者(mutator)3. 與const有關(guān)的錯(cuò)誤總是在編譯時(shí)發(fā)現(xiàn)4. [摘]If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message. A const function can be applied to a non-const object 5. 在C++中,一個(gè)對(duì)象的所有方法都接收一個(gè)指向?qū)ο蟊旧淼碾[含的this指針;常量方法則獲取了一個(gè)隱含的常量this指針 void func_name() const; 以上說(shuō)明函數(shù)func_name()不會(huì)改變*this。當(dāng)你把this指針看成函數(shù)func_name()的一個(gè)不可見參數(shù)就理解了 void func_name(T *this) (no const) void func_name(const T *this) (const)6. 常量函數(shù)可以被任何對(duì)象調(diào)用,而非常量函數(shù)則只能被非常量對(duì)象調(diào)用,不能被常量對(duì)象調(diào)用,如:
const
7. 在類中允許存在同名的常量函數(shù)和非常量函數(shù),編譯器根據(jù)調(diào)用該函數(shù)的對(duì)象選擇合適的函數(shù) 當(dāng)非常量對(duì)象調(diào)用該函數(shù)時(shí),先調(diào)用非常量函數(shù); 當(dāng)常量對(duì)象調(diào)用該函數(shù)時(shí),只能調(diào)用常量函數(shù); 如果在類中只有常量函數(shù)而沒(méi)有與其同名的非常量函數(shù),則非常量與常量對(duì)象都可調(diào)用該常量函數(shù);如:
輸出結(jié)果:non-const function f is calledconst function f is called
輸出結(jié)果:const function f is calledconst function f is called8. 以下代碼試圖修改類的數(shù)據(jù)成員,引起編譯錯(cuò)誤
posted on 2009-04-22 23:09 pear_li 閱讀(807) 評(píng)論(0) 編輯 收藏 引用 所屬分類: C++