C++常量(const)的使用


#include <iostream>    

using namespace std;

class MyClass
{
public:
    int GetValue() const ;
    int GetValue()
    {
        return x + y;
    }
    int GetMax()
    {
        return x > y ? x : y;
    }
    int GetMin() const
    {
        //p += 3;//錯誤,常函數成員不能更新數據
        return x < p ? x : y; //正確,p可以被使用
    }
    static void Display(const int &r)
    {
        cout << "所引用的對象為" << r << endl;
    }
    static void Display_no_const(int &r)
    {
        cout << "所引用的對象為" << r << endl;
    }
    MyClass(int a, int b) :x(a), y(b) //構造函數只能通過列表初始化的形式對常量成員進行初始化
    {
        cout << z << "<<<<";
    }
     const int z = 3;//定義時進行初始化,不需要在構造函數中進行初始化
private:
    int p = 1;
    const int x, y;
    
};

int MyClass::GetValue() const
{
 
    return x * y;
}

int main(void)
{
    const MyClass m1(2, 3);
    MyClass m2(5, 6);
    const int i = 0;
    int j = 5;
    // m1.z++; 錯誤,不能給常量賦值
    cout << m1.GetValue() << "<- first one" << endl;
    cout << m2.GetValue() << "<- second one\n";
    //m1.GetMax(); //錯誤,不能用常對象調用非常函數成員
    cout << m1.GetMin() << endl;
    //cout << m1.z;

    MyClass::Display(i);
    MyClass::Display(j); //可以從“int”轉換為“const int &”
    
    // MyClass::Display_no_const(i); //錯誤, 無法將參數 i 從“const int”轉換為“int &”
    return 0;
}
/*常量的總結:
1.常數據類型(const int i = 0;): 定義時就要初始化。
2.類中的 常對象(const MyClass m1(2, 3);):常對象一旦被定義即表示對象的成員也變成常類型, 即不能對其修改
若要修改需要加關鍵字 mutable 修飾
3.類中的 常數據成員:在類的實例化對象時,由於定義類時的數據成員為常數據類型,故需要在實例化對象時進行初始化
常數據成員,即通過構造函數初始化列表的方式實現,也可在定義類的常數據成員時進行初始化。常數據成員一樣也不可以修改。
4.類中的 常函數成員:可以實現函數的重載(如:GetValue()的重載);
                     常成員函數可以修改靜態數據成員,因為靜態數據不屬於對象,而是類的屬性。
                     還可以修改全局變量,其他對象的成員變量,被 mutable 修飾的成員變量;
                     不能更新任何數據成員;
                     不能調用非常函數成員;    
5.常引用(const int &r):常引用所引用的對象不能被修改;
*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM