初始化列表initializer_list

初始化列表定义在<initializer_list>,初始化列表简化了参数数量可变的函数的编写,初始化列表的所有的元素都应该是同一种数据类型

由于定义了列表中允许的类型,所以初始化列表是安全的;

#include <iostream>
#include <initializer_list>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int makeSum(std::initializer_list<int> lsh)
{
    int total = 0;
    for(auto i : lsh)
    {
        total += i;
    }
    return total;
}

int main(int argc, char** argv) 
{
    //int arrayInt[10];
    //for(int i = 0;i != 10;++i)
    //{
    //    arrayInt[i] = i + 1;
    //}
    std::cout <<  "makeSum({1,3,4,5,6,9}) : " << makeSum({1,3,4,5,6,9}) << std::endl;

    return 0;
}

结构是:

makeSum({1,3,4,5,6,9}) : 28

但是在main函数内这么写就是错误的

std::cout <<  "makeSum({1,3,4,5,6,9}) : " << makeSum({1,3,4,5.0}) << std::endl;

 

猜你喜欢

转载自www.cnblogs.com/boost/p/10353475.html