C++ const member function
不能修改 class non-static member data 也不能 call 其他非 const member function 的 member function。
宣告 function 時在最後面加個 const 的 function,ex:
1 | int GetIndex() const; |
Declaring a member function with the const keyword specifies that the function is a “read-only” function that does not modify the object for which it is called. A constant member function cannot modify any non-static data members or call any member functions that aren’t constant.
compiler 會檢查 const member function 是否有改到 member data、return value 是否為 pointer 或 reference,如果改到 member data 或傳回可以讓外界修改 member data 時 compiler 會 error。可以透過這個特性反向檢查一個原本非 const 的 member function 是否有修改到 member data。
如果要在 const member function 中修改特定 member data,可以在該 member data 的宣告前面加上 mutable。
Ref
- 《Effective C++》
- http://msdn.microsoft.com/zh-tw/library/6ke686zh.aspx