c++ - 这段代码有什么问题 - 在 C++ 中通过引用传递值?

标签 c++

所以我一直在尝试在 C++ 中创建一个计算数字阶乘的阶乘函数。

#include <iostream>
using namespace std;

int factorial(int& x)
{
  int b=x-1;

  if(x>1)
    return(x*=factorial(b));
  else
    return 1;
}

int main()
{
  int a;

  cout<<"Enter the number to get factorial (and press enter):\n";
  cin>>a;
  factorial(a);
  cout<<endl<<a;

  return 0;
}

上面的代码有效,但是如果我替换这段代码

return(x*=factorial(b));

return(x*=factorial(x-1));

这是行不通的。 它报告一条错误消息:“从类型为‘int’的右值对类型为‘int&’的非常量引用的初始化无效”,有人可以解释一下吗,我是初学者。

最佳答案

x - 1不是左值:它不指定存储,因此,您不能分配给/修改它。想一想:x - 1 *= <something>没有意义。因此,将右值传递给采用非 const 的函数是非法的。引用。

关于c++ - 这段代码有什么问题 - 在 C++ 中通过引用传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20301125/

相关文章:

c++ - boost::pool 默认 block 数

c++ - 处理空格字符作为输入

c++ - 如何通过更好的抽象来避免 typeid?

c++ - 无法找到 -libmysql 或 undefinder 引用 -mysqllib 和 mysql 库

c++ - 如何实现一个微型 RTSP 服务器?

c++ - 无法让 SFINAE 工作

Android JNI 本地引用表,转储当前状态

c++ - 使用 CreateEvent 创建/打开一个已经存在的偶数是否会重置信号?

c++ - LibCds:Michael Hashmap 和 Split Order List

c++ - 在命令行 C++ 上显示进度