Variable number of parameters in function in C++(C ++中函数中可变数量的参数)
问题描述
如何在我的 C++ 函数中使用可变数量的参数.
How I can have variable number of parameters in my function in 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 函数.维基百科列出了C++ 示例代码.
These are called Variadic functions. Wikipedia lists example code for C++.
可移植地实现可变参数C编程中的函数语言,标准的 stdarg.h 标头应该使用文件.年长的varargs.h 标头已被弃用赞成 stdarg.h.在 C++ 中,应使用头文件 cstdarg.
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
cstdargshould be used.
要创建一个可变参数函数,一个省略号 (...) 必须放在参数列表的结尾.在 - 的里面函数体,一个变量必须定义类型 va_list.那么宏 va_start(va_list, last fixedparam), va_arg(va_list, cast type),va_end(va_list) 可以使用.为了例子:
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 ++中函数中可变数量的参数
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
