(C++) 初始化列表 std::initializer_list
构造时直接使用初始化列表
T object { arg1, arg2, ... }; (1)
T { arg1, arg2, ... } (2)
new T { arg1, arg2, ... } (3)
Class { T member { arg1, arg2, ... }; }; (4)
Class::Class() : member{arg1, arg2, ...} {... (5)
赋值使用初始化列表
T object = {arg1, arg2, ...}; (6)
function( { arg1, arg2, ... } ) (7)
return { arg1, arg2, ... } ; (8)
object[ { arg1, arg2, ... } ] (9)
object = { arg1, arg2, ... } (10)
U( { arg1, arg2, ... } ) (11)
Class { T member = { arg1, arg2, ... }; }; (12)
使用初始化列表初始化实例
struct S {
std::string str1;
int a1;
std::string str2;
std::string str3;
};
S s1 {"abc", 1, "bbb", "ccc"}; // ok, will init in order
S s2 {"abc", 1, {"bbb"}, "ccc"}; // ok
std::pair<std::string, int> p {"10086", 10010};
std::vector<std::pair<std::string, int>> v {
{"10000", 200},
{"10010", 300},
{"10086", 400},
};
注意:这种{...}形式的初始化参数,是没有类型信息的,不能直接作为变量。
使用 std::initializer_list
An object of type std::initializer_list is a lightweight proxy object that provides access to an array of objects of type const T.
A std::initializer_list object is automatically constructed when:
- a braced-init-list is used to list-initialize an object, where the corresponding constructor accepts an std::initializer_list parameter
- a braced-init-list is used as the right operand of assignment or as a function call argument, and the corresponding assignment operator/function accepts an std::initializer_list parameter
- a braced-init-list is bound to auto, including in a ranged for loop
Initializer lists may be implemented as a pair of pointers or pointer and length. Copying a std::initializer_list does not copy the underlying objects
参考
分类:
C++
标签:
C++ / template
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构