VA_LIST是在C语言中解决变参问题的一组宏,所在头文件:#include <stdarg.h>,用于获取不确定个数的参数。
VA_LIST的用法:
首先在函数里定义一具VA_LIST型的变量,这个变量是指向参数的指针;
然后用VA_START宏初始化刚定义的VA_LIST变量;
然后用VA_ARG返回可变的参数,VA_ARG的第二个参数是你要返回的参数的类型(如果函数有多个可变参数的,依次调用VA_ARG获取各个参数);
最后用VA_END宏结束可变参数的获取。
以下是一个定义一个参数个数不确定的函数的简单例子:
#include <cstdarg>
#include <iostream>
using namespace std;
double average ( int num, ... )
{
va_list arguments; // A place to store the list of arguments
double sum = 0;
va_start ( arguments, num ); // Initializing arguments to store all values after num
for ( int x = 0; x < num; x++ ) // Loop until all numbers are added
sum += va_arg ( arguments, double ); // Adds the next value in argument list to sum.
va_end ( arguments ); // Cleans up the list
return sum / num; // Returns some number (typecast prevents truncation)
}
int main()
{
cout<< average ( 3, 12.2, 22.3, 4.5 ) <<endl;
cout<< average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) <<endl;
}