Specifying default parameter when calling C++ function

前端 未结 5 507
慢半拍i
慢半拍i 2020-12-09 18:23

Suppose I have code like this:

void f(int a = 0, int b = 0, int c = 0)
{
    //...Some Code...
}

As you can evidently see above with my cod

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 18:44

    There isn't a reserved word for this, and f(a,,c) is not valid either. You can omit a number of rightmost optional parameters, as you show, but not the middle one like that.

    http://www.learncpp.com/cpp-tutorial/77-default-parameters/

    Quoting directly from the link above:

    Multiple default parameters

    A function can have multiple default parameters:

    void printValues(int x=10, int y=20, int z=30)
    {
        std::cout << "Values: " << x << " " << y << " " << z << '\n';
    }
    

    Given the following function calls:

    printValues(1, 2, 3);
    printValues(1, 2);
    printValues(1);
    printValues();
    

    The following output is produced:

    Values: 1 2 3
    Values: 1 2 30
    Values: 1 20 30
    Values: 10 20 30
    

    Note that it is impossible to supply a user-defined value for z without also supplying a value for x and y. This is because C++ does not support a function call syntax such as printValues(,,3). This has two major consequences:

    1) All default parameters must be the rightmost parameters. The following is not allowed:

    void printValue(int x=10, int y); // not allowed
    

    2) If more than one default parameter exists, the leftmost default parameter should be the one most likely to be explicitly set by the user.

提交回复
热议问题