注册 登录
编程论坛 C++教室

[求助]如何实现变长参数函数

C维 发布于 2007-09-22 22:36, 596 次点击
就是类似printf这要的函数?
3q
2 回复
#2
HJin2007-09-23 00:05
回复:(C维)[求助]如何实现变长参数函数

see below, brother.

==============

#include <iostream>
#include <cstdarg> // for va_list, va_start, va_end, va_arg

using namespace std;

bool debug = false;

void DebugOutput(const char* formartString, ...)
{
va_list ap;

if(debug)
{
va_start(ap, formartString);
vfprintf(stderr, formartString, ap);
va_end(ap);
}
}

void SquareInts(int counter, ...)
{
int temp;
va_list ap;
va_start(ap, counter);
for(int i=0; i<counter; ++i)
{
temp = va_arg(ap, int);
cout<<temp*temp<<" ";
}
va_end(ap);

cout<<endl;
}

int main()
{
debug = true;

DebugOutput("This is the debug output\n");
DebugOutput("int %d\n", 13);
DebugOutput("My name is %s and I am %d years old\n", "John Doe", 20);
DebugOutput("lots of integers here %d %d %d %d %d\n", 5, 7, 6, -3, 90);

cout<<"---------------------------------------------------------"<<endl;
SquareInts(3, 40, 23, -20);

return 0;
}

#3
C维2007-09-23 09:16
不是这种实现方式的有没有?
1