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

查看:184
本文介绍了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() code> 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天全站免登陆