一个c++/Qt下定义可变参函数的小例子

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define cout qDebug() << "[ " << __FILE__ << ":" << __LINE__<< " ]";
typedef QStringList strlist;
#define listAppend(...)\
{}

#define CUSTOMER_FUNC(funcname)\
    inline funcname##_func(){\
    return   1;          \
    }

int addNums(int a/*参数的个数*/,...){
    int sum = a;
    va_list ap;

    va_start(ap, a); // use variable arg list
    while(a--)
        sum+= va_arg(ap,int);
    va_end(ap);

    return sum;
}

void printMsg(int num1,int num2,const char* msg,...){

    QString tmp;

    va_list args;
    tmp += "[ " + QString(msg) + " ] ";

    va_start(args,msg);

    QString str = QString(va_arg(args,char*));
    if(!str.trimmed().isEmpty()) {
        tmp += "[ " + str + " ] ";
    }
    va_end(args);

    qDebug() << QString("(%1,%2) ").arg(num1).arg(num2) + tmp;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << addNums(3,3,4,5);
    qt_message_output(QtDebugMsg,"just test the function");

    printMsg(3,1,"she is a girl","she is so beatiful","but i don't know her name..");

    cout;
    Q_FOREVER // for(;;)
    return a.exec();
}

你可能感兴趣的:(Qt相关技术,C++编程)