以前发现可变参数我用得并不多, 不过最近却发现它带来了很多方便....
以下是C语言示例代码:
#include <stdio.h> #include <stdarg.h> int print(char* fmt, ...) { char buffer[1024] = {0}; va_list va; va_start(va, fmt); vsnprintf(buffer, sizeof(buffer), fmt, va); va_end(va); return printf(buffer); } int main(int argc, char** argv) { print("%s %d %c\n", "女孩不哭", 100, 65); return 0; }
注意,可变参数函数是C语言中的, 所以如果在C++中使用时要这样定义函数:
int __cdecl print(char* fmt, ...)
这个在Windows编程中却也很有用, 比如在显示一个错误时:
我以往的做法是:
char buf[128] = {0}; wsprintf(buf, "error:%08x", GetLastError()); MessageBox(NULL, buf, NULL, MB_OK | MB_ICONEXCLAMATION);
现在, 变量也可以不用定义了, 直接一句话就搞定:
MsgBox(NULL,NULL,MB_OK | MB_ICONEXCLAMATION, "%s %d %c", "女孩不哭", 100, 'A');
女孩不哭(QQ:191035066)@2012-05-10 22:41:13 @ http://www.cnblogs.com/nbsofer