[英]different types of initialization in C++
我正在學習 C++,並且對不同類型的初始化感到困惑。
你可以做:
T a;
據我所知,它有時會初始化a
有時不會,這取決於T
是否具有默認構造函數。
你也可以這樣做:
T a(); // or
T a(1, 2, 3... args);
; (在某些情況下):
T a = 1; // implicitly converted to T sometimes?
; 如果沒有構造函數:
T a = {1, 2, 3, 4, 5, 6};
; 並且:
T a = T(1, 2, 3);
.
如果你想在堆上分配,有
T a = new T(1, 2, 3);
還有別的事嗎?
我想知道是否 a) 我已經涵蓋了所有類型的初始化和 b) 何時使用每種類型?
你犯了幾個錯誤。 我會清理他們的。
// Bog-standard declaration.
// Initialisation rules are a bit complex.
T a;
// WRONG - this declares a function.
T a();
// Bog-standard declaration, with constructor arguments.
// (*)
T a(1, 2, 3... args);
// Bog-standard declaration, with *one* constructor argument
// (and only if there's a matching, _non-explicit_ constructor).
// (**)
T a = 1;
// Uses aggregate initialisation, inherited from C.
// Not always possible; depends on layout of T.
T a = {1, 2, 3, 4, 5, 6};
// Invoking C++0x initializer-list constructor.
T a{1, 2, 3, 4, 5, 6};
// This is actually two things.
// First you create a [nameless] rvalue with three
// constructor arguments (*), then you copy-construct
// a [named] T from it (**).
T a = T(1, 2, 3);
// Heap allocation, the result of which gets stored
// in a pointer.
T* a = new T(1, 2, 3);
// Heap allocation without constructor arguments.
T* a = new T;
T a = 1; // 有時會隱式轉換為 T?
如果 T 具有復制構造函數,則可以這樣做。
T ();
這聽起來更像是返回類型 T 的“a”的 function 聲明
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.