天天看点

常用的C++11,14,17 新特性列表初始化

文章目录

  • 列表初始化

列表初始化

列表初始化在C++11中被提出, 列表初始化可以作用于任意的类型

  • 对于之前版本中需要初始化的任何地方,我们都可以使用列表初始化替换
  • 列表初始化可以将堆上创建的数组直接初始化
  • 通过initializer_list + 列表初始化可以很方便的实现变长参数的传入
#include<cstdio>
using namespace std;

class Node{
    public:
    int x,y; 
};

#include <initializer_list>
 
template<typename T>
void println(std::initializer_list<T> args)
{
	for (const T &item : args) {
		cout << item;
	}
	cout << endl;
}
int main(){
    Node node{1,2};
    cout << node.x << endl;
    cout << *(new int{2}) << endl;
    cout << *(new int[] {3,4}) + 1 << endl;
    // error: 不能类型变窄 
    //cout << *(new int[] {3.0,4}) << endl; 
    println({11,12,13});
}
           

但是列表初始化也不是万能的,还是有一些地方是没法使用默认的列表初始化的,比如:

  1. 含有protected 或者 privated 成员
#include<cstdio>
using namespace std;

class Node{
    public:
    int x,y; 
    protected:
    int z;
};

int main(){
    Node node{1,2,3};
}
           
  1. 含有基类或虚函数
#include<cstdio>
using namespace std;
class base{};
class Node: public base{
    public:
    int x,y; 
    virtual void f(){};
    protected:
    int z;
};

int main(){
    Node node{1,2,3};
}
           

要避免以上问题,只需要自实现一下列表初始化函数就好了:

#include<cstdio>
using namespace std;
class base{};
class Node: public base{
    public:
    int _x,_y; 
    virtual void f(){};
    Node(int x,int y, int z):_x(x),_y(y),_z(z){}
    protected:
    int _z;
};

int main(){
    Node node{1,2,3};
    cout << node._x << endl;
}
           

继续阅读