简体   繁体   English

c ++默认参数值

[英]c++ default parameters value

I would like to make sure that this method call is correct. 我想确保这个方法调用是正确的。 I have three arguments, and one defaults to a null QString. 我有三个参数,一个默认为null QString。

double funcApply(double* param, QString expr=NULL);

and the call is 和电话是

funcApply(param);

In function body, I test whether second argument expr is NULL or not, and proceed accrodingly. 在函数体中,我测试第二个参数expr是否为NULL,然后进行累加。 Will this call behave as expected, or misbehave? 这个电话会表现得像预期的那样,还是行为不端?

Thanks and regards. 谢谢并恭祝安康。

It depends on what you expect it to behave like. 这取决于你期望它的行为。

Technically, expr will not be NULL since it's not a pointer, but its contents will be empty. 从技术上讲, expr不会为NULL因为它不是指针,但其内容将为空。 (assuming you mean QString ). (假设你的意思是QString )。

Of course, if you have something like #define QString char* , then expr will be NULL , but I doubt you have that. 当然,如果你有类似#define QString char*东西,那么expr将为NULL ,但我怀疑你有。

I have errors 'redefinition of default parameter' and 'ambiguous call to overloaded function' at compile time 我在编译时有错误'重新定义默认参数'和'对重载函数的模糊调用'

For some reason, you are not allowed to repeat a default argument once it is given. 出于某种原因,一旦给出,您将不被允许重复默认参数。 If you have the default value in your header file, like: 如果头文件中有默认值,例如:

double funcApply(double* param, QString expr=NULL);

the implementation must not repeat it, but be something like 实现不能重复它,但有点像

double funcApply(double* param, QString expr /*=NULL*/)
{
    // do something
}

If you actually test the expr parameter for NULL and do two different things, you might be better off with two separate functions that do these "different things" 如果您实际测试了expr参数为NULL并执行了两个不同的事情,那么使用两个执行这些“不同的事情”的独立函数可能会更好

 double funcApply(double* param);
 double funcApply(double* param, QString expr);

and avoid this problem. 并避免这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM