1 const 后綴
成員函式,在引數串列之后加 const,可宣告為 常量成員函式,即該函式對于成員變數,只可讀不可寫
例如,Date 類中的三個常量成員函式:GetYear()、GetMonth() 和 GetDay()
class Date { public: int GetYear() const { return y; } int GetMonth() const { return m; } int GetDay() const { return d; } void AddYear(int n); // add n years private: int y, m, d; };
當在 GetYear() 中,修改成員變數 y 時,編譯會報錯
// error : attempt to change member value in const function
int Date::GetYear() const
{
return ++y;
}
注意 1):常量成員函式,在類外實作時,const 后綴不可省略
// error : const missing in member function type int Date::GetYear() { return y; }
注意 2):成員變數前有 mutable,則在常量成員函式中,也可修改成員變數
class Date { // ... private: mutable int y; }; // ok, even changing member value in const function int Date::GetYear() { return ++y; }
2 this 指標
const 成員函式,可被 const 或 non-const 型類物件呼叫,如 GetYear(),而 non-const 成員函式,只能被 non-const 物件呼叫,如 AddYear()
void func(Date& d, const Date& cd) { int i = d.GetYear(); // OK d.AddYear(1); // OK int j = cd.GetYear(); // OK cd.AddYear(1); // error }
任何成員函式,都有一個隱含的形參,即指向該類物件的 this 指標,它通常由編譯器隱式的生成,通過 this 指標,類物件才能呼叫成員函式
一般的,this 指標默認指向 non-const 物件,因此,const 類物件,無法通過 this 指標呼叫 non-const 函式
// 默認的 this 指標,指向 non-const 物件 Date * const this;
而 const 成員函式,通過引數后的 const 后綴,修改其 this 指標指向 const 型物件,此時,const 物件便可呼叫 const 成員函式
// 常量成員函式中的 this 指標,指向 const 物件 const Date * const this;
3 const 介面
上文的 func() 函式中,形參用 const 來修飾,可保證資料傳遞給函式,而本身不被修改,是設計 "介面" 的一種常用形式
void func(Date& d, const Date& cd) { // ... ... }
特殊情況下,想要 const 物件呼叫 non-const 成員函式,則可用 const_cast 移除物件的 const 屬性,具體形式為: const_cast<T>(expression)
void func(Date& d, const Date& cd) { int j = cd.GetYear(); // OK const_cast<Date&>(cd).AddYear(1); // const 物件呼叫 non-const 成員函式 }
這種做法,破壞了用 const 來指定 "介面" 的本意,并不推薦
參考資料
《C++ Programming Language》4th ch 16.2.9.1
《C++ Primer》5th ch 7.1.2
《Effective C++》3rd Item 3, item 27
《More Effective C++》 Item 2
原文鏈接: http://www.cnblogs.com/xinxue/
專注于機器視覺、OpenCV、C++ 編程
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/386452.html
標籤:C++
上一篇:在tkinter環境中,顯示輸入的級別n和起始行a(xa,ya)b(xb,yb)
下一篇:Docker 安裝&卸載