C++11常用特性介绍——列表初始化

一、列表初始化

1)C++11以前,定义初始化的几种不同形式,如下:

  int data = 0;   //赋值初始化

  int data = {0};   //花括号初始化

  int data(0);  //构造初始化

2)C++11以旧语法中花括号初始化形式为基础,设计了列表初始化语法,统一了不同的初始化形式

  a)数据类型 变量{初始化列表}

  //聚合类型

  struct Persion

  {

    char name[64];

    struct Date//成员是聚合类型

    {

      int year;

      int month;

      int day;

    }Age;

  };

  //

  class Student

  {

  public:

    Student(int year,int month,int day) : _year(year),_month(month),_day(day) {}

    friend std::ostream& operator << (std::ostream &os, Student const & s)

    {

      os << s._year << "-" << s._month <<  "-" << s._day;

    }

  private:

    int _year;

    int _month;

    int _day;

  }

 

  int main()

  {

    int a{1};

    std::cout << a << std::endl;

 

    double b{1.1};

    std::cout << b << std::endl;

    //聚合类型(任意类型的数组)

    int c[]{1,2,3,4,5};

    copy(c,c + sizeof(c) / sizeof(c[0]),ostream_iterator<decltype(*c)>(cout, " "));

    std::cout << std::endl;

    //

    Persion persion{"张三",2019,11,14};

    std::cout << persion.name << persion.year << persion.day << std::endl;

 

    Student student{2019,11,14};

    std::cout << student << std::endl;

  }

  聚合类型

  1)任意类型的数组

  2)满足特定条件的类:

    a、无自定义的构造函数

    b、无私有或保护的非静态成员变量

    c、无基类

    d、无虚函数

    e、无通过“=”或者“{}”丰类声明部分被初始化的非静态成员变量

  3)聚合类型的元素或者成员可以是聚合类型也可以是非聚合类型

  4)对聚合类型使用列表初始化,相当于用列表初始化的值作为参数,调用相应的构造函数。

  b)变长初始化列表:initializer_list

  class Num

  {

  public:

    Num(std::initializer_list list)

    {

      for(auto i : list)

      {

        _vector.push_back(i);

      }

    }

    friend std::ostream& operator << (std::ostream &os, Num n)

    {

         //copy(n._vector.begin(),n._vector.end(),ostream_iterator<decltype(n._vector[0]>(os," ");

      for(auto i : n_vector)

      {

        os << i << " " ;

      }

      return os;

    }

  private:

    std::vector<int> _vector;

  }

 

  int main()

  {

    Num num{1,2,3,4,5,6,7};

    std::cout << num << std::endl;

  }

  initializer_list作为轻量级的列表容器,不但可以用在构造函数中,也可以作为普通函数的参数,传递不定数量的实参,

  相对于传统标准容器,效率更高(轻量级列表容器,仅保存初始化列表元素的引用,而非其副本)

posted on 2019-11-14 17:20  zhangnianyong  阅读(432)  评论(0编辑  收藏  举报