首页 > 编程语言 > 详细

(C++)C++怎样编写不确定参数个数的函数

时间:2019-10-25 13:36:41      阅读:118      评论:0      收藏:0      [点我收藏+]

C++定义的函数是可以支持函数参数个数不确定的。VA_LIST是在C++语言中解决变参问题的一组宏,所在头文件:#include <stdarg.h>,用于获取不确定个数的参数同时使用...代替多个参数,调用时只需要根据需要传入多个参数。

VA_LIST的用法:

  1. 首先在函数里定义一具VA_LIST型的变量,这个变量是指向参数的指针;
  2. 然后用VA_START宏初始化刚定义的VA_LIST变量;
  3. 然后用VA_ARG返回可变的参数,VA_ARG的第二个参数是你要返回的参数的类型(如果函数有多个可变参数的,依次调用VA_ARG获取各个参数);
  4. 最后用VA_END宏结束可变参数的获取。

参考代码:求多个数得平均值

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>

(C++)C++怎样编写不确定参数个数的函数

原文:https://www.cnblogs.com/qiulidong/p/11737019.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!