2017-04-13 70 views
2

我看到一個函數,它接受一個std :: vector的引用,並且傳遞給它的參數讓我感到困惑,因爲發生了什麼。它看起來像這樣:在這個std :: vector構造函數中發生了什麼?

void aFunction(const std::vector<int>& arg) { } 


int main() 
{ 
    aFunction({ 5, 6, 4 }); // Curly brace initialisation? Converting constructor? 

    std::vector<int> arr({ 5, 6, 4 }); // Also here, I can't understand which of the constructors it's calling 

    return 0; 
} 

謝謝。

回答

1

這叫做std::initializer_list。它自C++ 11以來就在那裏。

以下是reference manual的工作原理。

5

爲對象通過這樣的結構來創建你需要提供構造函數接受std::initializer_liststd::vectorone (8)

vector(std::initializer_list<T> init, 
     const Allocator& alloc = Allocator()); 

你可以看到,以及在該網頁上的例子:

// c++11 initializer list syntax: 
std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"}; 

注:C++ 11還允許通過大括號對對象進行初始化:

Someobject { 
    Someobject(int){} 
}; 

Someobject obj1(1); // usual way 
Someobject obj2{1}; // same thing since C++11 

,但你必須要小心,如果對象已男星提到它會被用來代替之前:

std::vector<int> v1(2); // creates vector with 2 ints value 0 
std::vector<int> v2{ 2 }; // creates vector with 1 int value 2 

注2:你的問題列表如何創建它的文檔中描述:

std :: initializer_list對象在以下情況下自動構造:

在列表初始化中使用braced-init-list,包括函數調用列表初始化和賦值表達式

一個支撐,初始化列表勢必汽車,包括在遠程for循環

+0

是如何初始化器列表從大括號列表中創建?它是初始化列表的一部分轉換構造函數嗎? – Zebrafish

+0

謝謝。我永遠不會停止學習這種語言。 – Zebrafish

相關問題