无法更改函数中的值 [英] Unable to change values in a function

查看:151
本文介绍了无法更改函数中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始开发,对这个新手问题很抱歉。

I'm starting with developing, sorry about this newbie question.

我需要创建一个在2个vars之间交换值的函数。

I need to create a function that swap values between 2 vars.

我写了这段代码,但在vars中没有做任何更改,我应该更改什么?我的错误是什么?

I have wrote this code, but no changes are made in vars, What should I change? What is my mistake?

#include <iostream>
using namespace std;

void swap_values( int x, int y);
int main(void) {
   int a,b;    
   a = 2;   
   b = 5;  
   cout << "Before: " << a << " " << b << endl; 
   swap_values( a,b );   
   cout << "After: " << a << " " << b  << endl;   
}  
void swap_values( int x, int y ){
   int z;
   z = y;
   y = x;
   x = z;
}


推荐答案

void swap_values( int& x, int& y )
{
   int z;
   z = y;
   y = x;
   x = z;
}

pass-by-value pass-by-reference 是主要编程语言中的关键概念。在C ++中,除非指定by-reference,否则会出现 pass-by-value

pass-by-value and pass-by-reference are key concepts in major programming languages. In C++, unless you specify by-reference, a pass-by-value occurs.

它不是传递给函数的原始变量,而是副本。

It basically means that it's not the original variables that are passed to the function, but copies.

这就是为什么,在函数之外,变量保持不变 - 因为在函数内部,

That's why, outside the function, the variables remained the same - because inside the functions, only the copies were modified.

如果您通过引用( int& x,int& y ),对原始变量。

If you pass by reference (int& x, int& y), the function operates on the original variables.

这篇关于无法更改函数中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆