Where to put default parameter value in C++?

This question already has an answer here:

  • Default value of function parameter 4 answers

  • Default parameter values must appear on the declaration, since that is the only thing that the caller sees.

    EDIT: As others point out, you can have the argument on the definition, but I would advise writing all code as if that wasn't true.


    You can do either, but never both. Usually you do it at function declaration and then all callers can use that default value. However you can do that at function definition instead and then only those who see the definition will be able to use the default value.


    The most useful place is in the declaration (.h) so that all users will see it.

    Some people like to add the default values in the implementation too (as a comment):

    void foo(int x = 42,
             int y = 21);
    
    void foo(int x /* = 42 */,
             int y /* = 21 */)
    {
       ...
    }
    

    However, this means duplication and will add the possibility of having the comment out of sync with the code (what's worse than uncommented code? code with misleading comments!).

    链接地址: http://www.djcxy.com/p/28574.html

    上一篇: 将列表作为默认函数参数的奇怪行为

    下一篇: 在C ++中放置默认参数值的位置?