简体   繁体   中英

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.

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. 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. (assuming you mean QString ).

Of course, if you have something like #define QString char* , then expr will be NULL , but I doubt you have that.

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"

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

and avoid this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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