0

For example,a function that can take unlimited (or, more precisely, a very big number) amounts of the same type arguments, let's say integer, and then make all the passed integers have a value of 5.

What i ask is, can i,if i can,make a function with a non-fixed amount of parameters.

void setIntToFive(UNKNOWN AMOUNT OF INTS){
    //a for loop to assign a value to all the passed arguments
}

Then call it with different amounts of arguments every time

int a;
int b = 5;
setIntToFive(a,b);
int c;
setIntToFive(a,b,c);//Notice how i add another argument.

So, is there a way to make this, besides making the parameter an array.(i think it wouldn't work that way)

4

1 回答 1

2

您可以使用可变参数

本质上

double average ( int num, ... )
{
    va_list arguments;
    double sum = 0;

    va_start ( arguments, num );
    for ( int x = 0; x < num; x++ )
    sum += va_arg ( arguments, double );
    va_end ( arguments );

    return sum / num;
}

va_list 是一个保存所有传入参数的结构,va_start 将参数分配到该列表中。va_end 在使用后清理列表。num 是传递的参数数量。

查看 MSDN 了解更多信息。

于 2013-09-16T19:56:51.170 回答