C++定义的函数是可以支持函数参数个数不确定的。VA_LIST是在C++语言中解决变参问题的一组宏,所在头文件:#include <stdarg.h>,用于获取不确定个数的参数同时使用...代替多个参数,调用时只需要根据需要传入多个参数。
VA_LIST的用法:
参考代码:求多个数得平均值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#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; } |
来自 <https://zhidao.baidu.com/question/715169725722507325.html>
原文:https://www.cnblogs.com/qiulidong/p/11737019.html