Missing default argument - compiler error

前端 未结 5 930
無奈伤痛
無奈伤痛 2021-01-31 15:17
void func ( string word = \"hello\", int b ) {

  // some jobs

}

in another function

 //calling 
 func ( \"\", 10 ) ;

When I have compiled it, compi

相关标签:
5条回答
  • 2021-01-31 15:56

    The error message is proper. If the default argument is assigned to a given parameter then all subsequent parameters should have a default argument. You can fix it in 2 ways;

    (1) change the order of the argument:

    void func (int b, string word = "hello");
    

    (2) Assign a default value to b:

    void func (string word = "hello", int b = 0);
    
    0 讨论(0)
  • 2021-01-31 16:02

    Parameters with default values have to come at the end of the list because, when calling the function, you can leave arguments off the end, but can't miss them out in the middle.

    Since your arguments have different types, you can get the same effect using an overload:

    void func ( string word, int b ) {
    
      // some jobs
    
    }
    
    void func ( int b ) { func("hello", b); }
    
    0 讨论(0)
  • 2021-01-31 16:03

    The arguments with a default value have to come in the end of the argument list.

    So just change your function declaration to

    void func(int b, string word = "hello")
    
    0 讨论(0)
  • 2021-01-31 16:10

    You can't have non-default parameters after your default parameters begin. Put another way, how would you specify a value for b leaving word to the default of "hello" ?

    0 讨论(0)
  • 2021-01-31 16:20

    You cannot fix it without changing anything!

    To fix it, you can use overloading:

    void func ( string word, int b ) {
      // some jobs
    }
    
    void func ( string word ) {
        func( word, 999 );
    }
    
    void func ( int b ) {
        func( "hello", b );
    }
    
    0 讨论(0)
提交回复
热议问题