9-2 使用列表初始化

9.2 使用列表初始化

1. 隐式调用构造函数

#include <string>

struct C
{
C(std::string a, int b) {}
C(int a) {};
}

void foo(C) {}
C bar()
{
return {"world", 5};
}

int main()
{
int x = {5}; //拷贝初始化
int x2{8}; //直接初始化

C c1 = {4}; //拷贝初始化
C c2{5}; //直接初始化

foo({8}); //拷贝初始化
foo({"hello",8}); //直接初始化

C c3 = bar(); //拷贝初始化
C* c4 = new C{"hi", 43}; //直接初始化
}

2. 标准容器初始化

​ 使用列表初始化能让标准容器像数组一样被创建。

#include <vector>
#include <list>
#include <set>
#include <map>
#include <string>

int main()
{
int x1[] = {1,2,3,4,5};
int x2[]{1,2,3,4,5};

std::vector<int> v1 = {1,2,3,4,5};
std::vector<int> v2{1,2,3,4,5};

std::list<int> l1 = {1,2,3,4,5};
std::list<int> l2{1,2,3,4,5};

std::set<int> s1 = {1,2,3,4,5};
std::set<int> s2{1,2,3,4,5};

std::map<std::string, int> m1 = {{"a",1}, {"b",2}, {"c",3}};
std::map<std::string, int> m2{{"a",1}, {"b",2}, {"c",3}};
}