人生是如此精彩,今天學習是爲了明天綻放
const 放在函數前面和後面的區別
我們常常會遇到這樣的代碼
const int& funs() const
總結:
第一個const 代表該函數的返回值無法被改變。
第二個const代表該函數不會對調用者(如classA a;a->funs()中的a對象)內部成員進行更改。
(一)前面放const
舉例,頭文件
class MyClass
{
public:
MyClass();
public:
const int& Funs (const int tmp_b) //這裏將參數傳遞給a成員變量
{
this->a = tmp_b;
return tmp_b;
}
int a;
};
嘗試調用
MyClass *temp_MyClass = new MyClass();
temp_MyClass->a = 10; //給a賦值
temp_MyClass->Funs(20); //調用該函數刷新a的值
printf("%d\n",temp_MyClass->a); //打印a爲20
在函數前面加const作用,調用下面這樣的會報錯。
int ret = temp_MyClass->Funs(20) = 1; //假設有人會這樣做2333
//最有可能是這樣做
if(temp_MyClass->Funs(20) = 1) //由於程序員疏忽大意,將==寫成=了
{
}
程序編譯不通過
提示不可更改。
(二)在後面加const
當我在函數後面添加const的時候
const int &Funs (const int tmp_b) const
{
this->a = tmp_b; //該句報錯,提示const修飾的無法改變調用者
//本身
return this->a;
}