C++ const常量對(duì)象、常量成員函數(shù)和常引用

01 常量對(duì)象

如果不希望某個(gè)對(duì)象的值被改變,則定義該對(duì)象的時(shí)候可以在前面加const關(guān)鍵字

class CTest
{
public:
    void SetValue() {}
private:
    int m_value;
};

const CTest obj; // 常量對(duì)象

02 常量成員函數(shù)

在類的成員函數(shù)后面可以加const關(guān)鍵字,則該成員函數(shù)成為常量成員函數(shù)。

  • 在常量成員函數(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;
}

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ǔ)句了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容