c++ - 函数原型(prototype)中的 "..."

标签 c++ syntax

我看到某人的 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/

相关文章:

c++ - BFMatcher knnMatch

c++ - C++ 中的 char 星 vector

unit-testing - HsqlDB : expected ; 上的触发语法

string - 在 Bash 中比较两个字符串时出现 "command not found"错误

c++ - ‘->’ token 之前的预期初始值设定项

c++ - 是否有 Perl 的 __DATA__ 段的 C++ 等价物(或等价技术)?

rust - 为什么对不明确的数字进行方法调用会导致错误?

asp.net-mvc - Razor 语法在 UI 标记方面是否提供了令人信服的优势?

c++ - 会发生的事情是在执行 throw 语句时抛出异常

php - 我的语法有什么问题? (PHP/HTML)