函数可变参数列表
#include <iostream>#include <cstdarg>
using namespace std;
/*
num: the num is number of arg that was passed from main().
*/
double sum(int num, ...)
{
va_list arg; // stores the list of arg
double sum = 0;
va_start(arg, num); // init the list
for (int i = 0; i < num; i++) {
sum += va_arg(arg, double); // return the next arg in the list
}
va_end(arg); // clear the list
return sum;
}
int main(void)
{
cout << sum(5, 1.0, 5.5, 7.8, 3.6, 2.5) << endl;
// Note that it's error as following.
// cout << sum(5, 1.0, 5.5, 7.8, 3, 2) << endl; // error because it wasn't consistent with double type for 3 and 2.
return 0;
}
小知识点从新扫描一遍。 小知识点谢谢分享
页:
[1]