[英]what's the difference between these two different initialization for a string in c++?
[英]Two different variable initializations in a C++ Class. What's the difference?
我是一個自學的初學者,所以我想我會問一些非常基本的問題,但是,我忽略了。
假設您在 C++ 中有一個名為aClass
的類,並且其中一個構造函數需要一個參數。 這兩種方法有什么區別?
第一:
aClass::aClass(int aVariable) : privateVariable(aVariable) {}
第二:
aClass::aClass(int aVariable) {
privateVariable = aVariable;
}
如果它們基本相同,那么兩者中哪一個更常見? 或者,出於什么原因人們傾向於使用而不是另一個?
謝謝!
第一個進行初始化,應該是首選。
第二個進行賦值(在默認初始化之后)。 它主要相當於:
aClass::aClass(int aVariable) : privateVariable() {
privateVariable = aVariable;
}
因此,如果privateVariable
不是默認可構造的,則privateVariable
。
即使這已經有一個公認的答案,讓我們詳細說明一下。
讓我們舉一個例子,其中一個有效,另一個無效:
class Foo
{
public:
Foo(int value);
private:
Foo();
int content;
};
class Bar
{
public:
Bar(int value);
private:
Foo foo;
};
構造函數的工作實現將是
Bar::Bar(int value) : foo(value) {}
但是,如果你想
Bar::Bar(int value)
{
foo = Foo(value);
}
會發生的是這不會編譯。 作為演示,我創建了http://cpp.sh/2vfwqk ,看看如果您嘗試運行它會發生什么。 然后取消注釋較低的實現並取消注釋上面的實現。
問題是,必須先調用Foo()
才能開始處理主體,因為foo
需要初始化。
初始化列表直接執行此操作。
(如果我完全省略了空構造函數而不是將它設為私有,則該示例也可以工作,但這樣更容易理解。)
另一件事是,如果Foo()
是公共的,它將構造兩個對象。 如果這些是輕量級的,沒問題,但如果空構造函數需要大量內存或時間,則不可取。
對於作為參考的成員,您非常需要它。
也許值得一讀: https : //www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.