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

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

问题描述

我可以使用默认参数的构造函数这样也许

Can I use default arguments in a constructor like this maybe

士兵(INT entyID,诠释HLTH = 100,INT EXP = 10,串NME):ENTITYID(entyID = globalID ++),健康(HLTH),经验(EXP),名(NME = SelectRandomName (实验))
{}

我想例如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....

如果我提供的初始化列表,无论什么我在构造函数提供获取,另一方面ofcourse覆盖每当我在构造函数中提供一个值,那么为什么我在首位,因为每个我的时间需要一个默认值的值为对象开始提供值...?

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的最后的函数的参数。不能提供的缺省参数参数在参数列表的中间,因为你正在尝试上面做的。要么重新安排你的参数(把 HLTH EXP 结尾),或者提供一个默认的参数为 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.

此外,你的构造函数初始化列表中似乎没有任何意义。什么是合格的点 entyID NME 从外面,如果你反正覆盖在构造函数初始化列表中的值?

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天全站免登陆