C++函數參數中的省略號用法分析


C++允許定義形參個數和類型不確定的函數。例如,C語言中的標准函數printf便使用這種機制。在聲明不確定形參的函數時,形參部分可以使用省略號“…”代替。“…”告訴編譯器,在函數調用時不檢查形參類型是否與實參類型相同,也不檢查參數個數。

例如:void ConnectData(int i,...)

在上面的代碼中,編譯器只檢查第一個參數是否為整型,而不對其他參數進行檢查。

對於可變參數的函數,需要進行特殊的處理。首先需要引用 <stdarg.h>頭文件,然后利用va_list類型和va_start、va_arg、va_end 3個宏讀取傳遞到函數中的參數值。

這幾個宏的定義如下(在 ANSI C 中):

type va_arg( va_list arg_ptr, type );void va_end( va_list arg_ptr );void va_start( va_list arg_ptr, prev_param );

說明如下:

va_start :sets arg_ptr to the first optional argument in the list of arguments passed to the function. The argument arg_ptr must have va_list type. The argument prev_param is the name of the required parameter immediately preceding the first optional argument in the argument list. If prev_param is declared with the register storage class, the macro’s behavior is undefined. va_start must be used before va_arg is used for the first time.

【 va_start函數將參數arg_ptr設置為可變參數列表的第一個參數。參數arg_ptr的類型必須為va_list。參數prev_param是在可變參數列表之前的那一個參數。(也就是說在 ANSI C 中,如果一個函數有可變參數,那么在該可變參數前必須有一個明確定義的參數,否則無法調用函數 va_start ,例如函數 int add(int i,...)是合法的,而函數 int add(...)是不合法的。)】

va_arg :retrieves a value of type from the location given by arg_ptr and increments arg_ptr to point to the next argument in the list, using the size of type to determine where the next argument starts. va_arg can be used any number of times within the function to retrieve arguments from the list.

【 va_arg函數將返回 arg_ptr 所指位置的值,並將 arg_ptr 指向下一個參數 】

va_end

After all arguments have been retrieved, va_end resets the pointer to NULL.

示例代碼:

#include<cstdarg>
#include<iostream>
using namespace std;

int add(int pre,...)  
//求和函數
{
    va_list arg_ptr;
    int sum=0;
    int nArgValue;
    sum+=pre;
    va_start(arg_ptr,pre);
    do
    {
        nArgValue=va_arg(arg_ptr,int);
        sum+=nArgValue;       
    }while(nArgValue!=0);   
//自定義結束條件是輸入參數為0
   va_end(arg_ptr);
    return sum;
}
int main()
{
   cout<<add(1,2,3,0)<<endl;  
//必須以0結尾,因為參數列表結束的判斷條件是讀到0停止
   return 0;
}


免責聲明!

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



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