本文介绍了在c ++中通过引用传递可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C ++中有一个可选的函数参数的问题
I'm having a problem with optional function parameter in C++
我想做的是写参数传递的可选参数的函数,所以我可以使用它在两种方式(1)和(2),但在(2)我真的不在乎什么是 mFoobar
的价值。
What I'm trying to do is to write function with optional parameter which is passed by reference, so that I can use it in two ways (1) and (2), but on (2) I don't really care what is the value of mFoobar
.
我尝试过这样的代码:
void foo(double &bar, double &foobar = NULL)
{
bar = 100;
foobar = 150;
}
int main()
{
double mBar(0),mFoobar(0);
foo(mBar,mFoobar); // (1)
cout << mBar << mFoobar;
mBar = 0;
mFoobar = 0;
foo(mBar); // (2)
cout << mBar << mFoobar;
return 0;
}
但它在
void foo(double &bar, double &foobar = NULL)
b $ b
与消息:
with message :
error: default argument for 'double& foobar' has type 'int'
是否可以解决它没有函数重载?
Is it possible to solve it without function overloading?
推荐答案
(可变)引用的默认参数必须是l值。最好的,我可以想,没有重载,是
The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is
static double _dummy_foobar;
void foo(double &bar, double &foobar = _dummy_foobar)
这篇关于在c ++中通过引用传递可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!