您的位置:首页 > 编程语言 > C语言/C++

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;
}


大家可能出现预定义宏错误,网上有修改,工作太忙,没空具体解析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息