列表初始化
C++11后为了能让自定义类型也能够快速被初始化新增 {}
内置类型变量
int a1 = { 10 };
int a2{ 11 };
int a3 = { 1 + 2 };
int a4{ 1 + 2 };
注意:列表初始化可以在{}之前使用等号,其效果与不使用=没有什么区别。
内置类型数组
int arr1[] = { 1,2,3 };
int arr2[]{ 1,2,3 };
标准容器
vector<int> v1{ 1,2,3 };
map<int, int> m{ {1,1},{2,2},{3,3} };
map是存储的键值对,{1,1}为键值对相当于其中的一个数据,这表明{}可以连续的套娃去初始化想要内容
自定义类型
无模板
struct A
{
A(int a = 0, int b = 0) : _a(a), _b(b) {}
void Print(){cout <<_a <<" "<<_b << endl; }
private:
int _a;
int _b;
};
有模板
template<class T>
struct B
{
B(T c = 0, T d = 0) : _c(c), _d(d) {}
void Print() { cout << _c << " " << _d << endl; }
private:
T _c;
T _d;
};
多个对象的列表初始化
template<class T>
struct C
{
//initializer_list<T> lt=={ 1,2,3,4 }
C(initializer_list<T> lt):_arr(lt)
{
int i = 0;
if (i == 0)
{
i = 1;
}
}
private:
vector<T> _arr;
};
结果:
测试
A a{ 1,2 };
a.Print();
B<int> b{ 3,4 };
b.Print();
C<int> c = { 1,2,3,4 };
区分初始化列表和列表初始化
初始化列表-》初始类中一系列的变量
列表初始化-》使用 {很多内容} 去初始化某个函数或类
初始化列表链接:https://blog.csdn.net/weixin_62551043/article/details/137408222?spm=1001.2014.3001.5502