initializer_list类型详解

This type is used to access the values in a C++ initialization list, which is a list of elements of type const T

1、类型的自动创建
Objects of this type are automatically constructed by the compiler from initialization list declarations, which is a list of comma-separated elements enclosed in braces:

auto il = { 10, 20, 30 };  // the type of il is an initializer_list 

2、定义在头文件中,但是可以不用声明就进行调用

3、initializer_list 类型变量之间的拷贝:对同一个对象的引用,不会增加新的copy,只是语义上的拷贝

copying an initializer_list object produces another object referring to the same underlying elements, not to new copies of them (reference semantics).

4、生命周期 lifetime
The lifetime of this temporary array is the same as the initializer_list object.

5、构造器:相对于其他类型的构造器具有优先权

struct myclass {
  myclass (int,int);
  myclass (initializer_list<int>);
  /* definitions ... */
};
myclass foo {10,20};  // calls initializer_list ctor
myclass bar (10,20);  // calls first constructor 

6、操作
操作
7、作为模板类型,初始化时需要进行类型说明

#include <string> //必须包含的头文件之一,有string类存在
void error_msg(initializer_list<string> ls) //输出错误信息
{
    for (auto beg = ls.begin(); beg != ls.end(); ++beg)
    {
        std::cout << *beg << " ";
    }
    cout << std::endl;
}

    initializer_list<string> ls = { "error  1","error  2" ,"error  3" ,"error  3" ,"error  1" }; //定义类型及其初始化
    initializer_list<int> li;
    error_msg(ls);

    // 向initializer_list中传递参数注意点:{} 括起来
    string expected = "expected";
    string actual = "expected";
    if (expected != actual)
    {
        error_msg({ "functionX",expected, actual });
    }
    else
    {
        error_msg({ "functionX",expected, actual });
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值