天天看點

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

大家可能出現預定義宏錯誤,網上有修改,工作太忙,沒空具體解析。

繼續閱讀