<分区>
在 C++ 中用作函数参数时如何设置引用变量的默认值?
<分区>
在 C++ 中用作函数参数时如何设置引用变量的默认值?
最佳答案
除非使用移动运算符或 const
引用,否则无法提供对临时值的引用:
void test (int j, double && d1=0.0)
// ^^ Move
{
//my codes
}
void test (int j, const double & d1=0.0)
// ^^^^^ Extend lifetime
{
//my codes
}
您为此函数声明了一个引用(输出)参数,表明该函数在不传递输出参数的情况下没有意义,因此默认值完全关闭(应该调用什么 test(j );
实际上呢?).
你的意思可能是在进入函数时重置输出参数:
void test (int j, double & d1) {
d1 = 0.0; // << Assure a certain output
//my codes
}
关于c++ - 引用变量的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38282490/