C++ const常量對(duì)象、常量成員函數(shù)和常引用
小林coding
— 1 —
常量對(duì)象
如果不希望某個(gè)對(duì)象的值被改變,則定義該對(duì)象的時(shí)候可以在前面加 const 關(guān)鍵字。
class CTest
{
public:
void SetValue() {}
private:
int m_value;
};
const CTest obj; // 常量對(duì)象
— 2 —
常量成員函數(shù)
在類的成員函數(shù)后面可以加 const 關(guān)鍵字,則該成員函數(shù)成為常量成員函數(shù)。
這里有兩個(gè)需要注意的點(diǎn):
在常量成員函數(shù)中不能修改成員變量的值(靜態(tài)成員變量除外);
也不能調(diào)用同類的 非 常量成員函數(shù)(靜態(tài)成員函數(shù)除外)。
class Sample
{
public:
void GetValue() const {} // 常量成員函數(shù)
void func(){}
int m_value;
};
void Sample::GetValue() const // 常量成員函數(shù)
{
value = 0; // 出錯(cuò)
func(); // 出錯(cuò)
}
int main()
{
const Sample obj;
obj.value = 100; // 出錯(cuò),常量對(duì)象不可以被修改
obj.func(); // 出錯(cuò),常量對(duì)象上面不能執(zhí)行 非 常量成員函數(shù)
obj.GetValue; // OK,常量對(duì)象上可以執(zhí)行常量成員函數(shù)
return 0;
}
— 3 —
常量成員函數(shù)重載
兩個(gè)成員函數(shù),名字和參數(shù)表都一樣,但是一個(gè)是 const,一個(gè)不是,那么是算是重載。
class Sample
{
public:
Sample() { m_value = 1; }
int GetValue() const { return m_value; } // 常量成員函數(shù)
int GetValue() { return 2*m_value; } // 普通成員函數(shù)
int m_value;
};
int main()
{
const Sample obj1;
std::cout << "常量成員函數(shù) " << obj1.GetValue() << std::endl;
Sample obj2;
std::cout << "普通成員函數(shù) " << obj2.GetValue() << std::endl;
}
執(zhí)行結(jié)果:
常量成員函數(shù) 1
普通成員函數(shù) 2
— 4 —
常引用
引用前面可以加 const 關(guān)鍵字,成為常引用。不能通過常引用,修改其引用的變量的。
const int & r = n;
r = 5; // error
n = 4; // ok!
對(duì)象作為函數(shù)的參數(shù)時(shí),生產(chǎn)該對(duì)象參數(shù)是需要調(diào)用復(fù)制構(gòu)造函數(shù)的,這樣效率就比較低。用指針作為參數(shù),代碼又不好看,如何解決呢?
可以用對(duì)象的引用作為參數(shù),防止引發(fā)復(fù)制構(gòu)造函數(shù),如:
class Sample
{
...
};
void Func(Sample & o) // 對(duì)象的引用作為參數(shù)
{
...
}
但是有個(gè)問題,對(duì)象引用作為函數(shù)的參數(shù)有一定的風(fēng)險(xiǎn)性,若函數(shù)中不小心修改了形參 o,則實(shí)參也會(huì)跟著變,這可能不是我們想要的,如何避免呢?
可以用對(duì)象的常引用作為參數(shù),如:
class Sample
{
...
};
void Func(const Sample & o) // 對(duì)象的常引用作為參數(shù)
{
...
}
這樣函數(shù)中就能確保不會(huì)出現(xiàn)無意中更改 o 值的語(yǔ)句了。
小林coding
免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。文章僅代表作者個(gè)人觀點(diǎn),不代表本平臺(tái)立場(chǎng),如有問題,請(qǐng)聯(lián)系我們,謝謝!