Why should default parameters be added last in C++ functions?

前端 未结 9 1628
轻奢々
轻奢々 2020-11-27 07:01

Why should default parameters be added last in C++ functions?

9条回答
  •  执笔经年
    2020-11-27 07:58

    As most of the answers point out, having default parameters potentially anywhere in the parameter list increases the complexity and ambiguity of function calls (for both the compiler and probably more importantly for the users of the function).

    One nice thing about C++ is that there's often a way to do what you want (even if it's not always a good idea). If you want to have default arguments for various parameter positions, you can almost certainly do this by writing overloads that simply turn around and call the fully-parameterized function inline:

     int foo( int x, int y);
     int foo( int y) {
         return foo( 0, y);
     }
    

    And there you have the equivalent of:

     int foo( int x = 0, int y);
    

提交回复
热议问题