正如在其他答案中已經解釋過的,這個任務的機制是向量的std::initializer_list
assignment operator。這使得以下可能具有任意值的大括號括初始化列表,儘管不是聚合std::vector<int>
:
std::vector<int> a;
a = {1,2,4}; // OK, vector& operator=(std::initializer_list<T>)
但是以下是不允許
int c[3];
c = {1,4}; // Error: arrays are not assignable
這是因爲陣列是不可轉讓。如果它是一種不同類型的聚合體,那麼這將起作用。例如,
struct Foo { int a, b, c; }; // aggregate
Foo f = {1, 2, 3}; // OK, aggregate initialization
f = { 1, 4 }; // OK
這裏,f.a
,f.b
和f.c
分別分配的值1, 4, 0
。
此外,還可以初始化非聚集,並在具有帶有與列表元素兼容的參數列表的非構造函數(非explicit
)的帶括號的初始化程序列表中進行賦值。例如,
struct Bar
{
Bar(int a, int b, int c) : a(a), b(b), c(c) {} // non-aggregate
int a, b, c;
};
Bar b0 = {1, 2, 3}; // OK
Bar b1 = {1,2}; // Error: number of elements must be 3
b0 = {11, 22, 33}. // Assignemnt OK
大多無關,但如果你不知道這件事,有一個'的std ::陣列'類:http://en.cppreference.com/w/cpp/container/array –
@Casey是的,它修復了它 – Rajeshwar