3 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
列表初始化
一個(gè)整數(shù)不能轉(zhuǎn)換為另一個(gè)不能保存其值的整數(shù)。例如,char to int是允許的,而不是int to char。 浮點(diǎn)值不能轉(zhuǎn)換為另一種不能保存其值的浮點(diǎn)類型.例如,允許浮動(dòng)到雙倍,但不允許雙倍浮動(dòng)。 浮點(diǎn)值不能轉(zhuǎn)換為整數(shù)類型. 整數(shù)值不能轉(zhuǎn)換為浮點(diǎn)類型.
void fun(double val, int val2) { int x2 = val; // if val==7.9, x2 becomes 7 (bad) char c2 = val2; // if val2==1025, c2 becomes 1 (bad) int x3 {val}; // error: possible truncation (good) char c3 {val2}; // error: possible narrowing (good) char c4 {24}; // OK: 24 can be represented exactly as a char (good) char c5 {264}; // error (assuming 8-bit chars): 264 cannot be // represented as a char (good) int x4 {2.0}; // error: no double to int value conversion (good)}
auto
auto z1 {99}; // z1 is an initializer_list<int>auto z2 = 99; // z2 is an int
結(jié)語(yǔ)
喜歡{}初始化而不是其他選項(xiàng),除非您有很強(qiáng)的理由不這樣做。

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
initializer_list<>
T
struct Foo { Foo() {} Foo(std::initializer_list<Foo>) { std::cout << "initializer list" << std::endl; } Foo(const Foo&) { std::cout << "copy ctor" << std::endl; }};int main() { Foo a; Foo b(a); // copy ctor Foo c{a}; // copy ctor (init. list element) + initializer list!!!}

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果我正在創(chuàng)建的對(duì)象在概念上持有我在構(gòu)造函數(shù)中傳遞的值(例如容器、POD結(jié)構(gòu)、Atomics、智能指針等),那么我將使用大括號(hào)。 如果構(gòu)造函數(shù)類似于普通函數(shù)調(diào)用(它執(zhí)行一些或多或少由參數(shù)化的復(fù)雜操作),那么我將使用普通函數(shù)調(diào)用語(yǔ)法。 對(duì)于默認(rèn)初始化,我總是使用大括號(hào)。 首先,我總是確信對(duì)象是初始化的,而不管它是一個(gè)“真實(shí)的”類,它有一個(gè)默認(rèn)的構(gòu)造函數(shù),它無(wú)論如何都會(huì)被調(diào)用,或者是內(nèi)置/POD類型。其次,在大多數(shù)情況下,它與第一條規(guī)則一致,因?yàn)槟J(rèn)的初始化對(duì)象通常表示“空”對(duì)象。
std::vector
:
vector<int> a{10,20}; //Curly braces -> fills the vector with the argumentsvector<int> b(10,20); //Parenthesis -> uses arguments to parametrize some functionality, vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.vector<int> d{}; //empty braces -> default constructs vector, which is equivalent //to a vector that is filled with zero elements
- 3 回答
- 0 關(guān)注
- 779 瀏覽
添加回答
舉報(bào)