C++可变长不确定类型的参数
2016-04-21 19:38
531 查看
#include "stdafx.h" #include <cstdarg> #include <string.h> #include "iostream" using namespace std; typedef struct Params { enum ParamsType{NILL ,INT,CHAR, CHARS, DBL}; ParamsType type; union { int noParams; int intParams; char charParam; char charParams[256]; double doubleParams; }; static const Params NullParams;//声明,空参数,使用默认的构造函数Params();从而他的type为NILL; Params(){ noParams=0;type = NILL; } explicit Params(int p){ intParams = p; type = INT;} explicit Params(char p){ charParam = p; type = CHAR;} explicit Params(char* p){ strcpy(charParams, p); type = CHARS;} explicit Params(double p){ doubleParams = p; type = DBL;} inline bool isNull() { return (type == NILL)?true:false; } bool operator==(int n) { if ( type == 0) return 0; else return 1; } }pt; void ParamterTest(Params num, ... ) { va_list para; va_start(para, num); Params argc; char str[256]; memset(str, 0, sizeof(str)); if (num.type == 1) sprintf_s(str,"%s%d",str, num.intParams); else if (num.type == 2) sprintf_s(str,"%s%c",str, num.charParam); else if (num.type == 3) sprintf_s(str,"%s%s",str, num.charParams); else if (num.type == 4) sprintf_s(str,"%s%f",str, num.doubleParams); while((argc = va_arg(para, Params))== 0) { if (argc.type == 1) sprintf_s(str,"%s%d",str, argc.intParams); else if (argc.type == 2) sprintf_s(str,"%s%c",str, argc.charParam); else if (argc.type == 3) sprintf_s(str,"%s%s",str, argc.charParams); else if (argc.type == 4) sprintf_s(str,"%s%0.1f",str, argc.doubleParams); } cout << str << endl; } int _tmain(int argc, _TCHAR* argv[]) { ParamterTest( pt("谢世乐"), pt('M') , pt(12), pt(33.33), pt(444)); return 0; }
大家可能出现预定义宏错误,网上有修改,工作太忙,没空具体解析。
相关文章推荐
- Lua编程示例(一):select、debug、可变参数、table操作、error
- C++可变参数的实现方法
- 浅析C/C++中的可变参数与默认参数
- c++11可变参数使用示例
- 从零开始学JAVA之可变参数
- C/C++中可变参数的用法详细解析
- C/C++宏定义的可变参数详细解析
- C/C++可变参数的使用
- Lua中的函数(function)、可变参数、局部函数、尾递归优化等实例讲解
- 解析Java的可变长参数列表及其使用时的注意点
- Java中支持可变参数详解
- Python可变参数函数用法实例
- Swift中的可变参数函数介绍
- linux内核中printf函数实现原理分析
- [翻译][原创]C语言--变参函数详析
- 浅析可变参数列表的使用
- Python中函数的参数定义和可变参数
- 从printf谈可变参数函数的实现
- 黑马程序员 java5的新特性
- 可变参数函数和宏函数