天天看點

const成員函數

盡管函數名和參數清單都相同,void foo( ) const成員函數是可以與void foo( )并存的,可以形成重載! 我們假設調用語句為obj.foo(),如果obj為non-const對象,則調用foo()。如果obj為const對象,則調用foo()const。另外要注意,假如沒有提供foo()const,則const obj調用foo()将會報錯。但假如是沒有提供foo(),則non-const obj調用foo()const是完全沒有問題的。也就是說,non-const對象可以調用const函數(當然也可以調用non-const函數),但const對象不能調用non-const函數。

const關鍵字所起作用的本質,就是把隐藏着的預設的this指針參數,改成const類型。也就是說:假如void foo( )函數被編譯器改寫為 void foo(T* pThis),則void foo( ) const将會被改寫為void foo(const T* pThis) 。i.e. 在函數末尾添加一個const,就相當于在隐藏的this參數類型前加一個const.

這樣做有兩個效果,第一:編譯器将不允許foo()const修改pThis指向的對象的成員。第二、const對象隻能調用const成員函數,否則就會報錯說把const T* 轉化為T* 會丢失qualifier

------------------------------

//Only member functions declared as const can be invoked for a class object that is const. The const keyword is placed between the parameter list and the body of the member function. A const member function defined outside the class body must specify the constkeyword in both its declaration and its definition. For example:

class Screen

{

public:     

bool isEqual( char ch ) const;      // ... private:     

string::size_type    _cursor;     

string               _screen;      // ...

};

bool Screen::isEqual( char ch ) const

{     

return ch == _screen[_cursor];

}

原文

http://www.cnblogs.com/visayafan/archive/2011/11/24/2261849.html

繼續閱讀