(C++)C++怎樣編寫不確定參數個數的函數


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宏結束可變參數的獲取。

參考代碼:求多個數得平均值

#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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM