C++可变长不确定类型的参数

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


大家可能出现预定义宏错误,网上有修改,工作太忙,没空具体解析。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值