函数中的引用不会更改函数外部的项。C++
Reference in the function doesn't change item outside of it. C++
试图通过引用从函数中获取值,但似乎我一直在获取函数调用之前分配的值。
void third()
{
int summ = mainInput(3);
int second = 0;
cout << "You should pay " << fiveBill(summ, second) << second;
}
int fiveBill(int summ,int &two)
{
int five=0;
if (summ%2==0)
{
two = summ / 2;
}
else
{
two = (summ - 5) / 2;
five++;
}
while (two>4)
{
two -= 5;
five += 2;
}
return five;
}
变量"second"在我调用它时一直显示为0,而我确信它在函数内发生了变化。
在c++中,函数调用参数求值的顺序是故意不指定的。编译器完全有可能在计算对fiveBill(summ, second)
的调用之前将second
作为<<
的参数进行计算。只需在单独的先验表达式中调用fiveBill
,或将输出拆分为两个表达式。
相关文章:
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- C++:函数外部的超时功能
- 如何在函数外部访问函数中局部变量的值?
- 在成员函数外部封闭类的定义中需要默认成员初始值设定项
- 以延长构造函数外部 QT 对象的生存期
- 全局静态变量不"staying defined"函数外部
- C++ 函数外部丢失的指针对象
- 向量大小在构造函数外部恢复为 0
- 删除函数外部的实例化对象
- 在函数外部编写代码
- 为什么我不能添加到方法/函数外部的 ostringstream
- 用于在方法或函数外部声明的变量的内存
- SDL2 在函数外部加载字体会引发错误
- 如何在具有多态性的函数外部创建对象
- 在函数外部声明对象,将其作为引用传递,然后在函数内部创建它
- 向量未在函数C++外部更新
- 访问函数外部的堆栈对象
- 在c++中访问函数外部的数组
- 如何更新函数外部的数组(指向指针)