功能原型中的"......"

Sta*_*tan 3 c++ syntax

我看到有人的C++代码有如下的函数声明:

void information_log( const char* fmt , ...)
Run Code Online (Sandbox Code Playgroud)

或像块一样

catch(...)
{
}
Run Code Online (Sandbox Code Playgroud)

这是什么意思?

The*_*Man 8

...函数原型中的省略号用于将函数表示为可变参数.也就是说,它允许将可变数量的参数传递给函数.在这种形式中,函数必须为用户定义一些方式来准确指定它们呈现的参数数量,因为C++中的可变参数库函数无法动态地确定此信息.

例如,stdio函数printf就是原型的一个这样的函数:

int printf(const char *format, ...);
Run Code Online (Sandbox Code Playgroud)

据推测,根据两个原型之间的相似之处,information_log您描述的功能旨在反映大部分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;
}
Run Code Online (Sandbox Code Playgroud)


Pla*_*ure 7

这里真的是两个单独的问题,只是使用相同的符号.:-)

原型只是表明可变数量的参数.我真的可以说的是printf,如果你碰巧知道它,它有点像C的功能.该函数只是在需要时继续引入参数.

catch (...)代码只是意味着,捕捉任何异常.(通常你把它放在一些特定的catch块之后,这样就可以作为"全能"了.)