c++怎样编写不确定参数个数的函数

如题所述

c++怎样编写不确定参数个数的函数

C++定义的函数是可以支持函数参数个数不确定的。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;
}
温馨提示:答案为网友推荐,仅供参考
相似回答