构造函数中的默认参数 [英] default arguments in constructor

查看:37
本文介绍了构造函数中的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在这样的构造函数中使用默认参数吗

Can I use default arguments in a constructor like this maybe

Soldier(intentyID, int hlth = 100, int exp = 10, string nme) : entityID(entyID = globalID++), health(hlth), Experience(exp), name(nme = SelectRandomName(exp)){ }

我想要例如 exp = 10 默认情况下,但如果我在构造函数中提供它,则能够覆盖该值,否则它应该使用默认值.

I want for example exp = 10 by default but be able to override this value if I supply it in the constructor otherwise it should use the default.

我该怎么做,我知道我的方法行不通....

How can I do this, I know my approach does not work....

如果我在初始化列表中提供任何值,无论我在构造函数中提供什么都会被覆盖当然另一方面,每当我在构造函数中提供一个值时,为什么我每次都需要一个默认值为对象启动提供值...?

If I supply any value in the initialization list no matter whatever I supply in constructor gets overwritten ofcourse on the other hand whenever I supply a value in constructor then why do I need a default value in the first place as every time I am supplying a value for object initiation...?

我应该使用不同的重载构造函数还是你们有其他想法......?

Should I use different overloaded constructors or do you people have any other ideas....?

推荐答案

默认参数只能提供给连续范围的参数,该范围扩展到参数列表的末尾.简单地说,您可以为函数的 1, 2, 3, ... N last 个参数提供默认参数.您不能像上面尝试那样为参数列表中间的参数提供默认参数.重新排列您的参数(将 hlthexp 放在最后)或为 nme 提供默认参数.

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.

此外,您的构造函数初始值设定项列表似乎没有任何意义.如果您在构造函数初始值设定项列表中覆盖了它们的值,那么从外部传递 entyIDnme 有什么意义?

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?

这篇关于构造函数中的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆