简体   繁体   English

为什么该程序显示3个输出,为什么b覆盖a?

[英]Why does this program show 3 outputs, also why does b override a?

#include "stdafx.h"
#include <iostream>

using namespace std;

void silly(int & a, int & b)
{
    a=10;
    b=20;
    cout << a << "" << b << endl;
}


void main()
{
    int z=30;
    silly(z,z);
    cout << z << endl;
    system("Pause");

}

The output for this is: 输出为:

2020 20 2020年20

Why are there 3 outputs, and why does b override a? 为什么有3个输出,为什么b会覆盖a?

I'm asking because this is part of homework and I don't exactly understand the passing of variables especially strings/arrays. 我之所以问是因为这是家庭作业的一部分,我不太了解变量的传递,尤其是字符串/数组。

You are passing the reference of z to the silly() function. 您正在将z的引用传递给silly()函数。

When you change the value of a or b (both references to z) in silly(), it changes the value of z. 当您在silly()中更改a或b(均引用z)的值时,它将更改z的值。

So, at this line: 因此,在这一行:

  cout << a << "" << b << endl;

the value of z is 20, hence the output. z的值为20,因此输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM