我看到某人的 C++ 代码有如下函数声明:
void information_log( const char* fmt , ...)
或者像这样捕获 block
catch(...)
{
}
“...”是什么意思?
最佳答案
函数原型(prototype)中的省略号 ...
用于表示函数是可变的。也就是说,它允许将可变数量的参数传递给函数。在这种形式下,函数必须为用户定义某种方式来准确指定它们提供了多少个参数,因为 C++ 中的可变参数库函数无法动态确定此信息。
例如,stdio 函数 printf
就是这样一个函数,其原型(prototype)是:
int printf(const char *format, ...);
据推测,从两个原型(prototype)之间的相似性来看,您描述的 information_log
函数旨在反射(reflect) printf
的大部分功能,甚至可能在内部使用 printf
,或者它的同类之一。
以下是如何实现可变参数函数的示例:
// cstdarg provides access to the arguments passed to the ellipsis
#include <cstdarg> // or (#include <stdarg.h>)
#include <cstdio>
#include <cstring>
// Concatenates as many strings as are present
void concatenate(char ** out, int num_str, ...)
{
// Store where the arguments are in memory
va_list args;
// Find the first variadic argument, relative to the last named argument
va_start(args, num_str);
int out_len = 0;
int * lengths = new int[num_str];
char ** strings = new char*[num_str];
// Extract the strings from the variadic argument list
for(int i = 0; i < num_str; i++)
{
// Specify the position in the argument list and the type
// Note: You must know the type, stdarg can't detect it for you
strings[i] = va_arg(args, char *);
lengths[i] = strlen(strings[i]);
out_len += lengths[i];
}
// Concatenate the strings
int dest_cursor = 0;
(*out) = new char[out_len + 1];
for(int i = 0; i < num_str; i++)
{
strncpy( (*out) + dest_cursor, strings[i], lengths[i]);
dest_cursor += lengths[i];
}
(*out)[dest_cursor] = '\0';
// Clean up
delete [] strings;
delete [] lengths;
va_end(args);
}
int main()
{
char * output = NULL;
// Call our function and print the result
concatenate(&output, 5, "The ", "quick", " brown ", "fox ", "jumps!\n");
printf("%s", output);
delete [] output;
return 0;
}
关于c++ - 函数原型(prototype)中的 "...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3605296/