您正在寻找函数的无限数量参数的 c/c++ 定义。
你可以在这里看到-http://www.cplusplus.com/reference/cstdarg/va_start/
实现此类功能的简单方法如下:
1- 例如定义你的函数
void logging(const char *_string, int numArgs, ...)
第一个参数是你要使用的字符串。
第二个参数是你想要给出的无限参数的数量。如果您想计算开关中的占位符(例如 printf 中的 %d、%f),则不必使用此参数 - 提示:在循环中获取每个字符并查看它是否是您的占位符-。
我想先举一个例子,你如何调用这样的函数:
logging("Hello %0. %1 %2 %3", "world", "nice", "to", "meet you"); // infinite arguments are "world", "nice", ... you can give as much as you want
如您所见,我的占位符是数字。你可以使用任何你想要的东西。
2- 有宏,它初始化列表变量并获取参数的值:
va_list arguments; // define the list
va_start(arguments, numArgs); // initialize it, Note: second argument is the last parameter in function, here numArgs
for (int x = 0; x < numArgs; x++) // in a loop
{
// Note : va_arg(..) gets an element from the stack once, dont call it twice, or else you will get the next argument-value from the stack
char *msg = va_arg(arguments, char *); // get "infinite argument"-value Note: Second parameter is the type of the "infinite argument".
... // Now you can do whatever you want - for example : search "%0" in the string and replace with msg
}
va_end ( arguments ); // we must end the listing
如果您将每个占位符替换为无限参数值并打印新字符串,您应该会看到:
你好,世界。很高兴认识你
希望对你有帮助……