在C++11之前,对于一个值或者一个对象的初始化有很多种方法,我们会用到()、{ }、= 来进行初始化的工作,例如:

int a = 0;
int array[5] = {1,2,3,4,5};
vector<int> first;//初始化一个空的vector
vector<int> second(5,10);//初始化5个元素的vector对象,并全部赋值为10
vector<int> third(second.begin(),second.end());//利用second进行初始化
vector<int> fourth(third);//利用拷贝构造对third进行初始化

可以看到这些初始化的方法虽然多,对Value或Object的初始化缺乏统一的方法,而且对一些特殊的初始化操作不支持,比如:我想要对vector容器的进行初始化时传入1,2,3,4,5这些数字,那么该怎么做呢?我们可能会想到先初始化一个数组传入这些数字,利用数组给vector进行初始化,这个步骤要分为两步去做,太麻烦了。现在C++11引入了一致性的初始化方法,非常灵活和方便,对初始化操作进行了统一的处理。

int a{};//这种初始化的方式就比较友好,{}中为空,a会被默认的初始化为0
int array[]{0,1,2,3,4,5};
vector<int> v{1,2,3,4,5};
vector<string> cities{"BeiJing","ShangHai","GuangZhou","ShenZhen"};
complex<double> com{4.0,3.0};//complex是数学中的复数,第一个和第二个分别代表实数位和虚数位

使用{ }进行初始化,实际上是利用了一个事实:编译器看到{t1,t2…tn}时便做出一个initializer_list,它关联到一个array<T,n>。调用函数时该array内的元素可以被编译器分解逐一传递给函数。但是如果函数参数是一个initializer_list,这“包”数据(即{t1,t2…tn})将整体传入到函数中。
例如:上例中cities,{ }会形成一个initializer_list,背后有个array<string,4>。调用vector构造函数时,编译器找到了一个initializer_list 构造函数来接受initializer_list,而对于com来说,{ }会形成一个initializer_list,背后有一个array<double,2>,但是complex类中没有initializer_listctor,所以编译器会将array内的元素拆解开来传递给ctor。事实上,STL中所有的容器都有此类构造函数。

vector (initializer_list<value_type> il,const allocator_type& alloc = allocator_type());
list (initializer_list<value_type> il,const allocator_type& alloc = allocator_type());
deque (initializer_list<value_type> il,const allocator_type& alloc = allocator_type());
map (initializer_list<value_type> il,const key_compare& comp = key_compare(),const allocator_type& alloc = allocator_type());
set (initializer_list<value_type> il,const key_compare& comp = key_compare(),const allocator_type& alloc = allocator_type());
//上述为常见容器中含inisializer_list<T>的构造函数

以下为GCC中initializer_list源码:

// std::initializer_list support -*- C++ -*-// Copyright (C) 2008-2020 Free Software Foundation, Inc.
//
// This file is part of GCC.
//
// GCC is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// GCC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>./** @file initializer_list*  This is a Standard C++ Library header.*/#ifndef _INITIALIZER_LIST
#define _INITIALIZER_LIST#pragma GCC system_header#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else // C++0x#pragma GCC visibility push(default)#include <bits/c++config.h>namespace std
{/// initializer_listtemplate<class _E>class initializer_list{public:typedef _E       value_type;typedef const _E&    reference;typedef const _E&     const_reference;typedef size_t      size_type;typedef const _E*     iterator;typedef const _E*  const_iterator;private:iterator         _M_array;size_type          _M_len;// The compiler can call a private constructor.constexpr initializer_list(const_iterator __a, size_type __l): _M_array(__a), _M_len(__l) { }public:constexpr initializer_list() noexcept: _M_array(0), _M_len(0) { }// Number of elements.constexpr size_typesize() const noexcept { return _M_len; }// First element.constexpr const_iteratorbegin() const noexcept { return _M_array; }// One past the last element.constexpr const_iteratorend() const noexcept { return begin() + size(); }};/***  @brief  Return an iterator pointing to the first element of*          the initializer_list.*  @param  __ils  Initializer list.*  @relates initializer_list*/template<class _Tp>constexpr const _Tp*begin(initializer_list<_Tp> __ils) noexcept{ return __ils.begin(); }/***  @brief  Return an iterator pointing to one past the last element*          of the initializer_list.*  @param  __ils  Initializer list.*  @relates initializer_list*/template<class _Tp>constexpr const _Tp*end(initializer_list<_Tp> __ils) noexcept{ return __ils.end(); }
}#pragma GCC visibility pop#endif // C++11#endif // _INITIALIZER_LIST

使用{}给变量初始化:

int a;//只是被定义没有被初始化
int b{};//{}为空,默认被初始化为0
char* p;//只是被定义没有初始化
char* q{};//{}为空,默认初始化为NULL
int x {5.0};//ERROR,VS2017报告错误,double转int需要进行收缩转换
double y {5};//可行
char a(65);//会对应ASCII码自动进行转换为A
char a {65};//ERROR,不能进行转换
//注意,使用{}时不能进行收缩转换

使用Initializer_list进行构造:

vector(initializer_list<T> initlist){size_t size = initlist.size();reserve(size);_end = _begin;for(size_t i=0; i<size; ++i){cout << "initlist = " << *(initlist.begin() + i) << endl;*_end = *(initlist.begin() + i);_end++;}
}

类对象初始化和Initializer_list的相关推荐

  1. java对类对象初始化_Java类和对象初始化

    Java类和对象初始化Tag内容描述: 1.解析 Java 类和对象的初始化过程 由一个单态模式引出的问题谈起 北京高伟达西南分软 Java EE 软件工程师 三年 Java EE 项目经验 行业方向 ...

  2. 【C++】利用构造函数对类对象进行初始化

    运行环境:VS2017 一.对象的初始化 每一个对象都应当在它建立之时就有就有确定的内容,否则就会失去对象的意义. class Time {int hour = 0;int min = 0;int s ...

  3. 【C++】构造函数 利用构造函数对类对象进行初始化

    7个月之后的补充: 说真的,别再收藏这篇文章了,写的真的很拉跨,建议学习并收藏C++ 六个默认成员函数 + this指针_CPP的底层是哲学的博客-CSDN博客 也是我写的,质量会好很多!!!!!! ...

  4. java类初始化_Java的类/实例初始化过程

    昨天看到群里面有人分享了一道题目,我答错了,于是趁机了解了下Java的类/对象初始化过程: 程序的输出见文章最后 程序A主要考察的是 类实例初始化 .简单验证了下,类实例初始化过程如下:父类实例初始化 ...

  5. (22)C++ 类 对象

    C++ 类 & 对象 C++ 类定义 定义 C++ 对象 访问数据成员 类 & 对象详解 C++ 类成员函数 笔记 1.`::` 详解 2.类中的成员函数与 inline 3.C++中 ...

  6. java初始化实例化_Java对象的创建过程:类的初始化与实例化

    一.Java对象创建时机 我们知道,一个对象在可以被使用之前必须要被正确地实例化.在Java代码中,有很多行为可以引起对象的创建,最为直观的一种就是使用new关键字来调用一个类的构造函数显式地创建对象 ...

  7. 初始化列表||类对象作为类成员|| 静态成员

    初始化列表 作用: C++提供了初始化列表语法,用来初始化属性 语法:构造函数():属性1(值1),属性2(值2)... {} #include <iostream> using name ...

  8. Java对象的创建过程:类的初始化与实例化

    一.Java对象创建时机 我们知道,一个对象在可以被使用之前必须要被正确地实例化.在Java代码中,有很多行为可以引起对象的创建,最为直观的一种就是使用new关键字来调用一个类的构造函数显式地创建对象 ...

  9. Java类和对象初始化

    首先对Java 较为深层技术提几个问题(包含class 文件格式的了解): 1.类的访问权限在class二进制文件中怎么体现的? 2.类中static 区域 怎么初始化的,时间,顺序,特点是什么? 3 ...

  10. memset() 初始化类对象

    今天看到迅雷2014校招一道笔试题如下: [cpp] view plaincopy #include <iostream> using namespace std; class paren ...

最新文章

  1. python getattr_Python中的getattr()函数详解
  2. 一个基于SAP Hybris Commerce和微信的社交电商原型介绍
  3. WorldList5
  4. CSS3 新增选择器:伪类选择器和属性选择器
  5. 【转】Pycharm的激活
  6. Atitit.研发管理---TOGAF架构跟 (ADM开发方法)总结
  7. [DataAnalysis]机器学习数据类型和数据质量
  8. python用均值填充空值_用平均值填充空值
  9. 复合函数高阶求导公式_复合函数求导公式有哪些
  10. CSDN博客图片调整大小
  11. SNN 脉冲神经网络
  12. 字符串格式化-format()
  13. 分治法解决最近点对问题
  14. 机器学习吴恩达课程总结(一)
  15. Linux centos搭建web服务器
  16. linux修复笔记本电池电量,我戴尔笔记本电池损耗到百分之三十了!怎么修好啊!晕...
  17. 【​观察】得生态者得云天下 阿里、腾讯、浪潮、华为对决云计算2.0
  18. Sonar代码扫描常见规则总结
  19. mysql查询本周的周一(星期一)和周日(星期日)
  20. MySQL的四种事务隔离级别

热门文章

  1. 超人视觉怎么样/机器视觉培训适合报培训班吗
  2. join and list删除 and set集合 and 深浅拷贝
  3. OpenStack 快速进阶教程
  4. 单片机——LED点阵
  5. 深圳的住房公积金的那些事儿~(缴纳标准,用处用法)
  6. 解决git push报错:The requested URL returned error: 403
  7. 从新品抽奖小程序思考微信工具型小程序的发展
  8. 广义表的存储结构及其基本运算
  9. 软件开发人员如何记笔记
  10. svchost.exe不停下载