在所有的功能,我们见过这么远的一个函数的参数的数目,将需要必须提前知道(即使他们的默认值)。然而,有某些情况下它会很有用的。可以通过一个变量的函数的数量的参数。C提供的特殊specifier称为椭圆(又名“……”),允许精确的美国做这个。
因为很少使用的是椭圆的,危险的,我们强烈推荐你使用的网络,这被视为可选的CAN部分阅读。
利用椭圆函数的形式,把回报_型函数名称(参数列表_ _,……)。参数列表是一个或更多的_固定参数,就像正常的功能使用。(这是代表作为《椭圆的三期A row)必须始终是在负载参数的函数。任何参数传递到函数参数列表_必须匹配。捕获任何额外的椭圆的参数(如果有任何)。虽然这是不太准确的,它是有用的conceptually想的是椭圆的,持有的任何额外的参数数组_超越那些在参数列表。
最好的方式来了解是由椭圆的例子。让我们写一个简单的程序使用的是椭圆的。让我们说我们想写一个函数,测算平均一堆整数。我们做这样的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <cstdarg> // needed to use ellipses
// The ellipses must be the last parameter
double FindAverage(int nCount, ...)
{
long lSum = 0;
// We access the ellipses through a va_list, so let's declare one
va_list list;
// We initialize the va_list using va_start. The first parameter is
// the list to initialize. The second parameter is the last non-ellipse
// parameter.
va_start(list, nCount);
// Loop nCount times
for (int nArg=0; nArg < nCount; nArg++)
// We use va_arg to get parameters out of our ellipses
// The first parameter is the va_list we're using
// The second parameter is the type of the parameter
lSum += va_arg(list, int);
// Cleanup the va_list when we're done.
va_end(list);
return static_cast<double>(lSum) / nCount;
}
int main()
{
cout << FindAverage(5, 1, 2, 3, 4, 5) << endl;
cout << FindAverage(6, 1, 2, 3, 4, 5, 6) << endl;
}