gpt4 book ai didi

c++ - C++中函数中的可变参数数量

转载 作者:IT老高 更新时间:2023-10-28 12:40:27 28 4
gpt4 key购买 nike

如何在 C++ 中的函数中拥有可变数量的参数。

C# 中的模拟:

public void Foo(params int[] a) {
for (int i = 0; i < a.Length; i++)
Console.WriteLine(a[i]);
}

public void UseFoo() {
Foo();
Foo(1);
Foo(1, 2);
}

Java 中的模拟:

public void Foo(int... a) {
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}

public void UseFoo() {
Foo();
Foo(1);
Foo(2);
}

最佳答案

这些被称为 Variadic functions .维基百科列表 example code for C++ .

To portably implement variadic functions in the C programming language, the standard stdarg.h header file should be used. The older varargs.h header has been deprecated in favor of stdarg.h. In C++, the header file cstdarg should be used.

To create a variadic function, an ellipsis (...) must be placed at the end of a parameter list. Inside the body of the function, a variable of type va_list must be defined. Then the macros va_start(va_list, last fixed
param)
, va_arg(va_list, cast type), va_end(va_list) can be used. For example:

#include <stdarg.h>

double average(int count, ...)
{
va_list ap;
int j;
double tot = 0;
va_start(ap, count); //Requires the last fixed parameter (to get the address)
for(j=0; j<count; j++)
tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
va_end(ap);
return tot/count;
}

关于c++ - C++中函数中的可变参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1579719/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com