您的位置:首页 > 其它

initializer_list类型详解

2017-08-25 14:07 549 查看
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 });
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: