C\C++中函式後面加const
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
/* * 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
/*
* 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;
}
#include<iostream>
using namespace std;
int a=1,b=2;
int *p;
//codeblock c++11
const int* test1()//返回指標常量int const *test1()
{
p=&a;
return p;
}
int* const test2()//返回常量指標
{
p=&a;
return p;
}
int main()
{
int const *t1 = test1();
t1=&b;
cout<<*t1<<endl;
int *const t2 = test2();
*t2=3;
cout<<*t2<<endl;
return 0;
}
指標常量與常量指標的區別:https://blog.csdn.net/m0_37154839/article/details/84864312
---------------------
作者:蓀蓀
來源:CSDN
原文:https://blog.csdn.net/smf0504/article/details/52311207
版權宣告:本文為博主原創文章,轉載請附上博文連結!