default arguments in constructor

后端 未结 5 1984
失恋的感觉
失恋的感觉 2021-01-15 16:52

Can I use default arguments in a constructor like this maybe

Soldier(int entyID, int hlth = 100, int exp = 10, string nme) : entityID(entyID = globalID++), hea

相关标签:
5条回答
  • 2021-01-15 17:03

    Only trailing arguments can be default arguments. You would need to give nme a default argument or change the order of the arguments that the constructor takes so that hlth and exp come last.

    As regards the assignment you make in the initialiser list what happens there is that the member entityID gets assigned the value that is returned by the assignment of globalID++ to entyID which will be the value of entyID after the assignment. A similar thing happens for name.

    0 讨论(0)
  • 2021-01-15 17:07

    Default arguments can only be supplied to a continuous range of parameters that extends to the end of the parameter list. Simply speaking, you can supply default arguments to 1, 2, 3, ... N last parameters of a function. You cannot supply default arguments to parameters in the middle of the parameter list, as you are trying to do above. Either rearrange your parameters (put hlth and exp at the end) or supply a default argument for nme as well.

    Additionally, you constructor initializer list doesn't seem to make any sense. What was the point of passing entyID and nme from outside, if you override their values anyway in the constructor initializer list?

    0 讨论(0)
  • 2021-01-15 17:14

    I believe you can do this, however, all your defaulted args would need to go at the end. So, in your example, the constructor signature would be

    Soldier(int entyID, string nme, int hlth = 100, int exp = 10);
    
    0 讨论(0)
  • 2021-01-15 17:22

    All of the parameters with default arguments need to be after any required arguments. You should move the nme parameter before hlth.

    0 讨论(0)
  • 2021-01-15 17:24

    Arguments with default values must be the last arguments in the function declaration. In other words, there can not be any arguments without default values following one with a default value.

    0 讨论(0)
提交回复
热议问题