c++ - C++ [Xcode] 中可变数量的参数

标签 c++ xcode6

我对 C++ 中可变数量的参数有疑问。我使用 Xcode 编写代码。

这是我的代码:

#include <iostream>

int sum(int n, ...)
{
    int *p = &n;
    p++;

    int res = 0;
    for(int i=0; i<n; i++){
        res+=(*p);
        p++;
    }

    return res;
}

int main(int argc, const char * argv[]) {

    std::cout << sum(4, 1, 2, 3, 4);

    return 0;
}

sum(4, 1, 2, 3, 4) 应该返回值 10,但它返回 1606452732。

最佳答案

在 C++ 中,您使用模板元函数来执行此操作。这非常简单:

int sum(int u)
{return u;}  // Recursion-End

template<typename... Args>
int sum(int u, Args... rest)
{
    return u + sum(rest...);
}

试一试 online !

但是,正如我所认为的,使用 va_startva_end 的折旧 C 方式。您需要包含 cstdarg 并且在函数调用中您需要提供参数总数。它看起来像这样:

int sum(int argnum, ...)
{
    va_list arguments;
    int i;
    int sum = 0;

    va_start(arguments, argnum); /* Needs last known character to calculate
                                    the address of the other parameters */
    for(i = 0; i < argnum; ++i)
        sum += va_arg(arguments, int); /* use next argument */

    va_end(arguments);

    return sum;
}

试一试 online !

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

相关文章:

c++ - 如何在 sleep 时唤醒 std::thread

ios - 6.0.1 和表更改 "UILabel? does not have a member named ' 文本”

ios - 自动布局中固定和对齐之间的区别?

ios - SWRevealViewController插入对象:atIndex object cannot be nil

c++ - 试图修复一个字符串函数,它接受一个字符串并通过替换一些单词来改变它

c++ - 类标识符从不工作?

iOS8 应用程序在使用 HealthKit 的 Xcode6.0.1 上崩溃

ios - 如何在不使用 Storyboard 的情况下创建新的 Swift 项目?

c++ - Qt, C++, 如何退出 QThread

c++ - 为什么派生类没有vtable指针而是使用基类的vtable?