C ++中可变数量的参数? [英] Variable number of arguments in C++?

查看:47
本文介绍了C ++中可变数量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个接受可变数量参数的函数?这可能吗,怎么做?

How can I write a function that accepts a variable number of arguments? Is this possible, how?

推荐答案

您可能不应该这样做,而且您可能可以以更安全、更简单的方式做您想做的事情.从技术上讲,要在 C 中使用可变数量的参数,您需要包含 stdarg.h.从中您将获得 va_list 类型以及对其进行操作的三个函数,称为 va_start()va_arg()>va_end().

You probably shouldn't, and you can probably do what you want to do in a safer and simpler way. Technically to use variable number of arguments in C you include stdarg.h. From that you'll get the va_list type as well as three functions that operate on it called va_start(), va_arg() and va_end().

#include<stdarg.h>

int maxof(int n_args, ...)
{
    va_list ap;
    va_start(ap, n_args);
    int max = va_arg(ap, int);
    for(int i = 2; i <= n_args; i++) {
        int a = va_arg(ap, int);
        if(a > max) max = a;
    }
    va_end(ap);
    return max;
}

如果你问我,这是一团糟.它看起来很糟糕,不安全,而且充满了与您在概念上试图实现的目标无关的技术细节.相反,请考虑使用重载或继承/多态、构建器模式(如流中的 operator<<())或默认参数等.这些都更安全:编译器会更多地了解您'正在尝试这样做,有更多的场合可以在你炸掉你的腿之前阻止你.

If you ask me, this is a mess. It looks bad, it's unsafe, and it's full of technical details that have nothing to do with what you're conceptually trying to achieve. Instead, consider using overloading or inheritance/polymorphism, builder pattern (as in operator<<() in streams) or default arguments etc. These are all safer: the compiler gets to know more about what you're trying to do so there are more occasions it can stop you before you blow your leg off.

这篇关于C ++中可变数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆