C++参数带大括号 func({})

背景

看到一个函数调用的情况,如下:

 Func({
    
    task}, 1);

函数参数居然可以带大括号。

了解

原来这是C++11支持的{}初始化方式,叫做“初始化列表(initializer list)”。
比如下面几种

void func22(vector<int> aa)
{
    
    
    cout << "func22: ";
    for(int i=0; i<aa.size(); i++){
    
    
        cout << aa[i] << " ";
    }
    cout << endl;
}
void func33(initializer_list<int> aa)
{
    
    
    const int* a = aa.begin();
    cout << "func33: ";
    for(; a<aa.end(); ++a){
    
    
        cout << *a << " ";
    }
    cout << endl;
}

int main() {
    
    
    int dd2{
    
    23};    //值
    int aa[]{
    
    1,2,4};    //数组
    std::vector<int> va{
    
    2,3,4}; //容器

    func22({
    
    1,2,3});    //函数参数
    func33({
    
    3,4,5});
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40541268/article/details/126224787
今日推荐