01 常量對(duì)象
如果不希望某個(gè)對(duì)象的值被改變湾蔓,則定義該對(duì)象的時(shí)候可以在前面加const
關(guān)鍵字
class CTest
{
public:
void SetValue() {}
private:
int m_value;
};
const CTest obj; // 常量對(duì)象
02 常量成員函數(shù)
在類(lèi)的成員函數(shù)后面可以加const
關(guān)鍵字瘫析,則該成員函數(shù)成為常量成員函數(shù)。
- 在常量成員函數(shù)中不能修改成員變量的值(靜態(tài)成員變量除外);
- 也不能調(diào)用同類(lèi)的 非 常量成員函數(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;
}
03 常量成員函數(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
04 常引用
引用前面可以加const關(guān)鍵字媒熊,成為常引用奇适。不能通過(guò)常引用,修改其引用的變量的芦鳍。
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è)問(wèn)題裙顽,對(duì)象引用作為函數(shù)的參數(shù)有一定的風(fēng)險(xiǎn)性付燥,若函數(shù)中不小心修改了形參0,則實(shí)參也會(huì)跟著變愈犹,這可能不是我們想要的键科,如何避免呢?
可以用對(duì)象的常引用作為參數(shù)漩怎,如:
class Sample
{
...
};
void Func(const Sample & o) // 對(duì)象的常引用作為參數(shù)
{
...
}
這樣函數(shù)中就能確保不會(huì)出現(xiàn)無(wú)意中更改o值的語(yǔ)句了勋颖。