簡體   English   中英

我可以在C ++類中將成員變量聲明為const嗎?

[英]Can i declare member variable as const in class of c++?if yes,how?

我可以在C ++類中將成員變量聲明為const嗎?

您可以-將const放在類型名稱的前面。

class C
{
     const int x;

public:
      C() : x (5) { }
};

如果它不是成員,則可以聲明它。 注意,將變量聲明為const將對使用類的方式產生很大影響。 您肯定需要一個構造函數來初始化它:

class A {
    public:
        A( int x ) : cvar( x ) {}
    private:
        const int cvar;
};

當然,如果類的所有實例的值都相同,則最簡單的方法是這樣的:

class X
{
public:
    static const int i = 1;
};

或者,如果您不希望它是靜態的:

class X
{
public:
    const int i;
    X(int the_i) : i(the_i)
    {     
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM