變參函式
來自 cppreference.com
變長引數函式(例如 std::printf)是接受可變數量引數的函式。
要宣告一個變長引數函式,引數列表後面會出現一個省略號,例如 int printf(const char* format...);,前面可以有一個可選的逗號。有關語法、自動引數轉換和替代方案的更多詳細資訊,請參閱變長引數。
為了從函式體中訪問變長引數,提供了以下庫工具:
定義於標頭檔案
<cstdarg> | |
啟用對變長函式引數的訪問 (函式宏) | |
訪問下一個變長函式引數 (函式宏) | |
(C++11) |
複製變長函式引數 (函式宏) |
結束變長函式引數的遍歷 (函式宏) | |
儲存 va_start、va_arg、va_end 和 va_copy 所需的資訊 (型別定義) |
[編輯] 示例
執行此程式碼
#include <cstdarg> #include <iostream> void simple_printf(const char* fmt...) // C-style "const char* fmt, ..." is also valid { va_list args; va_start(args, fmt); while (*fmt != '\0') { if (*fmt == 'd') { int i = va_arg(args, int); std::cout << i << '\n'; } else if (*fmt == 'c') { // note automatic conversion to integral type int c = va_arg(args, int); std::cout << static_cast<char>(c) << '\n'; } else if (*fmt == 'f') { double d = va_arg(args, double); std::cout << d << '\n'; } ++fmt; } va_end(args); } int main() { simple_printf("dcff", 3, 'a', 1.999, 42.5); }
輸出
3 a 1.999 42.5
[編輯] 另請參閱
C 文件,關於變長引數函式
|