我們定義的類的成員函數中,常常有一些成員函數不改變類的數據成員,也就是說,這些函數是"只讀"函數,而有一些函數要修改類數據成員的值。如果把不改變數據成員的函數都加上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;
/*
* 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_ */
源文件中的實現
/*
* 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;
}