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