【问题标题】:Value doesn't change after passing by reference通过引用传递后值不会改变
【发布时间】:2019-04-17 05:55:06
【问题描述】:
#include<string.h>
#include<limits.h>
using namespace std;


void v6(char rq,int &cost)
{
    if(rq=='2')
        cost+=1;

    if(rq=='1')
        cost+=2;

    if(rq=='3')
        cost+=3;
}

int main()
{
    int cost=0;
    v6(2,cost);
    cout<<cost;
}

输出: 0

但是,c 的值(通过引用传递)并没有改变;请解释一下。

也使用过指针,但无济于事

【问题讨论】:

  • 您将2 传递为int 而不是char,因此函数中的条件不成立。调用 v6 为 v6('2',control,cost);
  • @Wander3r 你可以添加这个作为答案。

标签: c++ variables reference


【解决方案1】:

我对你的函数调用稍作改动应该会给你想要的行为

v6('2',cost);

您的if 语句检查char 而不是数字。要么应用上述更改,要么更改 if 语句

void v6(char rq,int &cost)
{
    if(rq==2)
        cost+=1;

    if(rq==1)
        cost+=2;

    if(rq==3)
        cost+=3;
}

【讨论】:

    【解决方案2】:

    您在函数调用中传递了Numeric 2 而不是char 2

    v6(2,cost); 必须替换为v6('2',cost);

    传递 2 传递 ASCII 等价物 2 (http://www.asciitable.com/)。

    '2' 的 ASCII 等效值是 50。所以,v6(50,cost);v6('2',cost); 会给你同样的结果。

    【讨论】:

      猜你喜欢
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 2021-03-05
      • 2014-11-15
      相关资源
      最近更新 更多