如何在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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud) 我想知道是否有任何方法可以动态地将参数传递给可变参数函数.即如果我有一个功能
int some_function (int a, int b, ...){/*blah*/}
Run Code Online (Sandbox Code Playgroud)
我接受用户的一堆值,我想要一些方法将这些值传递给函数:
some_function (a,b, val1,val2,...,valn)
Run Code Online (Sandbox Code Playgroud)
我不想写所有这些功能的不同版本,但我怀疑没有其他选择?
在以下C程序中,我收到警告:
warning #2030: '=' used in a conditional expression.
究竟是什么问题,我该如何避免这个?迭代变量参数的正确方法是什么?
#include <stdio.h>
#include <stdarg.h>
int Sum(int a, int b, ...)
{
int arg;
int Sum = a + b;
va_list ap;
va_start(ap, b);
while(arg = va_arg(ap, int))
{
Sum += arg;
}
va_end(ap);
return Sum;
}
int main(int argc, char *argv[])
{
printf("%d\n", Sum(1, 2, 4, 8));
return 0;
}
Run Code Online (Sandbox Code Playgroud) I understand this code calculates the sum of the args of a variable, however, I don't understand how it works. It looks really abstract to me. Can someone explain how the below works?
Thanks!
#include <stdio.h>
#define sum(...) \
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
int _sum(size_t count, int values[])
{
int s = 0;
while(count--) s += values[count];
return s;
}
int main(void)
{
printf("%i", sum(1, 2, 3));
}
Run Code Online (Sandbox Code Playgroud)