我怎样才能建立一个可以接收3或4个参数的函数? [英] How can I build a function that can receive 3 or 4 arguments ?
问题描述
我知道这是一个基本的问题,
I know it's a basic question ,
如何建立\\写一个可以接收3或4个参数的函数?
How can I build\write a function that can receive 3 or 4 arguments ?
或者更一般的,我怎么能写一个可以接收参数数目未知的函数?
Or more general , How can i write a function that can receive unknown number of arguments ?
谢谢!
推荐答案
要定义与未知数量的参数,第一个必须知道的功能。然后,你必须包括 STDARG.H
库使用它的功能来访问这些参数:va_start中,va_args,va_en和类型va_list
To define a function with an unknown number of arguments the first one must be known. Then you have to include the stdarg.h
library to access the arguments using it's functions: va_start, va_args, va_en and the type va_list.
在一般的函数被定义这种方式。请注意,第一个参数并不总是键入 INT
的。它可以是为const char *
有关你的论点更CONTROLE。在的printf()
功能为例。
In general the function is defined this way. Note that the first argument is not always of type int
. It can be const char *
for more controle on your arguments. for exemple in the printf()
function.
type myFunction(int n, ...)
{
int i;
va_list args;
va_start(args, n);
for (i=0; i<n; i++){
// your argument is va_arg(args, int);
//... do something with your aruments
}
va_end(args);
// return your value
}
检查这些资源,更多关于 STDARG.H
的 http://www.cplusplus.com/reference/cstdarg/
或 http://en.wikipedia.org/wiki/Stdarg.h
这篇关于我怎样才能建立一个可以接收3或4个参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!