本文介绍了在C ++中通过引用传递时,参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我们通过引用传递参数时,可以为函数的参数赋予默认值。在C ++中
Is it possible to give a default value to a parameter of a function while we are passing the parameter by reference. in C++
例如,当我尝试声明一个函数时:
For example, when I try to declare a function like:
virtual const ULONG Write(ULONG &State = 0, bool sequence = true);
当我这样做时会出现错误:
When I do this it gives an error:
推荐答案
你可以做一个const引用, - 一个。这是因为C ++不允许临时(在这种情况下的默认值)绑定到非const引用。
You can do it for a const reference, but not for a non-const one. This is because C++ does not allow a temporary (the default value in this case) to be bound to non-const reference.
这样做的一种方法是使用实际实例作为默认值:
One way round this would be to use an actual instance as the default:
static int AVAL = 1;
void f( int & x = AVAL ) {
// stuff
}
int main() {
f(); // equivalent to f(AVAL);
}
但实际使用非常有限。
这篇关于在C ++中通过引用传递时,参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!