這兩個選項之間有一個微妙但重要的區別。你在頂部有什麼叫做成員初始化列表。創建對象時,此列表中的成員將初始化爲您放入括號中的任何內容。
當你在構造函數體分配,該值是第一初始化,然後分配。我將在下面發佈一個簡短的例子。
例1:成員初始化
class foo
{
public:
foo(char c, int i);
private:
char exampleChar;
int exampleInt;
Bar exampleBar;
};
foo::foo(char c, int i):
exampleChar(c),
exampleInt(i),
exampleBar() //Here, a bar is being default constructed
{
}
例2:構造函數賦值
class foo
{
public:
foo(char c, int i, Bar b);
private:
char exampleChar;
int exampleInt;
Bar exampleBar;
};
foo::foo(char c, int i, Bar b):
//exampleChar(c),
//exampleInt(i),
//exampleBar()
{
exampleChar = c;
exampleInt = i;
exampleBar = someOtherBar; //Here, a bar is being assigned
}
這是它變得有趣。請注意,正在分配exampleBar
。在幕後,Bar
實際上首先被默認構建,即使您沒有指定。此外,如果你的Bar
比一個簡單的結構更復雜,你將需要確保實現賦值運算符,以便以這種方式初始化它。此外,爲了從成員初始化列表中初始化Bar
從另一個Bar
,您必須實現複製構造函數!
例3:在成員初始化使用拷貝構造函數
class foo
{
public:
foo(char c, int i, Bar b);
private:
char exampleChar;
int exampleInt;
Bar exampleBar;
};
foo::foo(char c, int i, Bar b):
//exampleChar(c),
//exampleInt(i),
exampleBar(b) //Here, a bar is being constructed using the copy constructor of Bar
{
exampleChar = c;
exampleInt = i;
}
「此代碼...並不意味着我在其他語言中使用規則」好吧,C++是不是那些其他語言之一。 C++中有很多與「其他語言」不同的東西(可能與其他語言中的其他語言有很多不同之處)。 –
非常類似的問題:http://stackoverflow.com/questions/1598967/benefits-of-initialization-lists,http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member -initialization-list,http://stackoverflow.com/questions/4589237/c-initialization-lists,可能更多 –