实例讲解在C++的函数中变量参数及默认参数的使用

2020-01-06 14:20:40于丽
易采站长站为您分析在C++的函数中变量参数及默认参数的使用,是C++函数入门学习中的基础知识,需要的朋友可以参考下  

包含变量参数列表的函数
如果函数声明中最后一个成员是省略号 (...),则函数声明可采用数量可变的参数。在这些情况下,C++ 只为显式声明的参数提供类型检查。即使参数的数量和类型是可变的,在需要使函数泛化时也可使用变量参数列表。函数的系列是一个使用变量参数列表的函数的示例。printfargument-declaration-list
包含变量参数的函数
若要访问声明后的参数,请使用包含在标准包含文件 STDARG.H 中的宏(如下所述)。

采用数量可变的参数的函数声明至少需要一个占位符参数(即使不使用它)。如果未提供此占位符参数,则无法访问其余参数。
当 char 类型的参数作为变量参数进行传递时,它们将被转换为 int 类型。同样,当 float 类型的参数作为变量参数进行传递时,它们将被转换为 double 类型。其他类型的参数受常见整型和浮点型提升的限制。

使用参数列表中的省略号 (...) 来声明需要变量列表的函数。使用在 STDARG.H 包含文件中描述的类型与宏来访问变量列表所传递的参数。有关这些宏的详细信息,请参阅 va_arg、va_copy、va_end、va_start。(处于 C 运行时库文档中)。
以下示例演示如何将宏与类型一起使用(在 STDARG.H 中声明):va_listva_endva_argva_start


// variable_argument_lists.cpp
#include <stdio.h>
#include <stdarg.h>

// Declaration, but not definition, of ShowVar.
void ShowVar( char *szTypes, ... );
int main() {
  ShowVar( "fcsi", 32.4f, 'a', "Test string", 4 );
}

// ShowVar takes a format string of the form
//  "ifcs", where each character specifies the
//  type of the argument in that position.
//
// i = int
// f = float
// c = char
// s = string (char *)
//
// Following the format specification is a variable 
// list of arguments. Each argument corresponds to 
// a format character in the format string to which 
// the szTypes parameter points 
void ShowVar( char *szTypes, ... ) {
  va_list vl;
  int i;

  // szTypes is the last argument specified; you must access 
  // all others using the variable-argument macros.
  va_start( vl, szTypes );

  // Step through the list.
  for( i = 0; szTypes[i] != ''; ++i ) {
   union Printable_t {
     int   i;
     float  f;
     char  c;
     char  *s;
   } Printable;

   switch( szTypes[i] ) {  // Type to expect.
     case 'i':
      Printable.i = va_arg( vl, int );
      printf_s( "%in", Printable.i );
     break;

     case 'f':
       Printable.f = va_arg( vl, double );
       printf_s( "%fn", Printable.f );
     break;

     case 'c':
       Printable.c = va_arg( vl, char );
       printf_s( "%cn", Printable.c );
     break;

     case 's':
       Printable.s = va_arg( vl, char * );
       printf_s( "%sn", Printable.s );
     break;

     default:
     break;
   }
  }
  va_end( vl );
}
//Output: 
// 32.400002
// a
// Test string