[英]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;
};
您正在嘗試通過靜態初始化構造初始化實例成員。 如果您希望這是一個類級變量(靜態),那么在變量前加上static關鍵字。
class Foo {
private:
static int myInt;
};
類變量必須標記為“靜態”。 如果您的變量是實例變量而不是類變量,則必須在構造函數或其他方法中對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.