这可能很容易,我可能只是错过了我面前的事情。但是,我无法弄清楚如何确保通过引用传递的函数参数可以被修改。基本上我需要以下内容:
bool calculate(double lat, double lon, double dep,
double &x, double &y, double &z)
{
if (x, y, AND z are NOT const)
{
perform the proper calculations
assign x, y, and z their new values
return true;
}
else //x, y, or z are const
{
return false;
}
}
“if”声明检查确实是我需要的全部
我再次道歉,如果这已经在这个网站上,或者它是一个标准的库函数,我就在我面前。我一直来到这里,几乎总能找到一个好的答案,但我已经在这里找不到任何东西了。
答案 0 :(得分:8)
如果你有double &x
那么它不是常数。如果你有const double &x
那么它就是常数。
在你的情况下 - 不需要检查,它们不是常量。该检查将在编译时间内自动执行。
见:
void func(double &x){ X=3.14; }
double d;
const double c_d;
func(d); // this is OK
func(1.54); // this will give an ERROR in compilation
func(c_d); // this will also give an ERROR in compilation
你根本无法使用常量调用想要(非const
)引用的函数。
这意味着编译器会为您找到一些错误 - 就像您的情况一样,您不必返回true
或false
,并且您无需检查它以尝试找到错误 - 你只需编译,编译器就会找到这些错误。