簡體   English   中英

正確的位置來初始化類變量?

[英]Correct place to initialize class variables?

初始化類數據成員的正確位置在哪里? 我在頭文件中有類聲明,如下所示:

foo.h中:

class Foo {
private:
    int myInt;
};

然后我嘗試在相應的.cpp文件中為myInt設置一個值:

Foo.cpp中:

int Foo::myInt = 1;

我為重新定義myInt而遇到編譯器錯誤。 我究竟做錯了什么???

你有什么是一個實例變量。 該類的每個實例都有自己的myInt副本。 初始化它們的地方是在構造函數中:

class Foo {
private:
    int myInt;
public:
    Foo() : myInt(1) {}
};

類變量是只有一個副本由類的每個實例共享的變量。 這些可以在您嘗試時初始化。 (參見JaredPar對語法的回答)

對於整數值,您還可以選擇在類定義中初始化靜態const權限:

class Foo {
private:
    static const int myInt = 1;
};

這是由無法更改的類的所有實例共享的單個值。

為了擴展Jared的答案,如果你想以現在的方式初始化它,你需要把它放在構造函數中。

class Foo
{
public:
    Foo(void) :
    myInt(1) // directly construct myInt with 1.
    {
    }

    // works but not preferred:
    /*
    Foo(void)
    {
        myInt = 1; // not preferred because myInt is default constructed then assigned
                   // but with POD types this makes little difference. for consistency
                   // however, it's best to put it in the initializer list, as above
                   // Edit, from comment: Also, for const variables and references,
                   // they must be directly constructed with a valid value, so they
                   // must be put in the initializer list.
    }
    */

private:
    int myInt;
};

它可以直接在頭文件中初始化,在c ++ 11或gnu ++ 11中:

int myInt = 1;

請參閱此文章“ C ++ 11花絮:非靜態數據成員初始化器

您正在嘗試通過靜態初始化構造初始化實例成員。 如果您希望這是一個類級變量(靜態),那么在變量前加上static關鍵字。

class Foo {
private:
  static int myInt;
};

類變量必須標記為“靜態”。 如果您的變量是實例變量而不是類變量,則必須在構造函數或其他方法中對其進行初始化。

暫無
暫無

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

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