C\C++學習--函式後面加const
阿新 • • 發佈:2019-02-11
https://blog.csdn.net/smf0504/article/details/52311207
c++ 在函式後加const的意義: 我們定義的類的成員函式中,常常有一些成員函式不改變類的資料成員,也就是說,這些函式是"只讀"函式,而有一些函式要修改類資料成員的值。如果把不改變資料成員的函式都加上const關鍵字進行標識,顯然,可提高程式的可讀性。其實,它還能提高程式的可靠性,已定義成const的成員函式,一旦企圖修改資料成員的值,則編譯器按錯誤處理。 const成員函式和const物件 實際上,const成員函式還有另外一項作用,即常量物件相關。對於內建的資料型別,我們可以定義它們的常量,使用者自定義的類也一樣,可以定義它們的常量物件。
1、非靜態成員函式後面加const(加到非成員函式或靜態成員後面會產生編譯錯誤) 2、表示成員函式隱含傳入的this指標為const指標,決定了在該成員函式中, 任意修改它所在的類的成員的操作都是不允許的(因為隱含了對this指標的const引用); 3、唯一的例外是對於mutable修飾的成員。 加了const的成員函式可以被非const物件和const物件呼叫 但不加const的成員函式只能被非const物件呼叫
char getData() const{ return this->letter;
}
c++ 函式前面和後面 使用const 的作用:
前面使用const 表示返回值為const
後面加 const表示函式不可以修改class的成員
請看這兩個函式
const int getValue();
int getValue2() const;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /* * FunctionConst.h */ #ifndef FUNCTIONCONST_H_ #define FUNCTIONCONST_H_ class FunctionConst { public: int value; FunctionConst(); virtual ~FunctionConst(); const int getValue( int getValue2() const; }; #endif /* FUNCTIONCONST_H_ */ |
原始檔中的實現
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /* * FunctionConst.cpp */ #include "FunctionConst.h" FunctionConst::FunctionConst():value(100) { // TODO Auto-generated constructor stub } FunctionConst::~FunctionConst() { // TODO Auto-generated destructor stub } const int FunctionConst::getValue(){ return value;//返回值是 const, 使用指標時很有用. } int FunctionConst::getValue2() const{ //此函式不能修改class FunctionConst的成員函式 value value = 15;//錯誤的, 因為函式後面加 const return value; } |