Why are these default arguments allowed?

后端 未结 3 1665
面向向阳花
面向向阳花 2021-01-19 03:14

I\'ve found this question, and I\'m completely baffled.

The answer says b is invalid, \"Non-static members can not be used as default arguments.\". That

3条回答
  •  庸人自扰
    2021-01-19 03:50

    Actually, default arguments are evaluated when the function is called, which is why this is okay. From the draft C++ standard section 8.3.6 Default arguments which says (emphasis mine going forward):

    Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. Parameters of a function declared before a default argument are in scope and can hide namespace and class member names.

    The following example from the same section gives us a rationale for why we can use static members but not non-static ones:

    [ Example: the declaration of X::mem1() in the following example is ill-formed because no object is supplied for the non-static member X::a used as an initializer.

    int b;
    class X {
        int a;
        int mem1(int i = a); // error: non-static member a
                             // used as default argument
        int mem2(int i = b); // OK; use X::b
        static int b;
    };
    

    The declaration of X::mem2() is meaningful, however, since no object is needed to access the static member X::b. Classes, objects, and members are described in Clause 9. —end example ]

提交回复
热议问题