C++ 中解析关于传值、传地址、传递引用的解析

传值,
  是把实参的值赋值给行参 
  那么对行参的修改,不会影响实参的值 
  
  传地址  ,
  是传值的一种特殊方式,只是他传递的是地址,不是普通的如int 
  那么传地址以后,实参和行参都指向同一个对象
  
  传引用  ,
  真正的以地址的方式传递参数 
  传递以后,行参和实参都是同一个对象,只是他们名字不同而已 
  对行参的修改将影响实参的值
 传递引用代码(实参、形参是同一个对象,交换成功):
 view plaincopy to clipboardprint?
#include "stdafx.h"  
#include <iostream>   
#include <time.h>  
using namespace std;  
 
void change(int& x,int& y);  
int main(){  
    int a = 10,b = 20;  
    int& x = a;  
    int& y = b;  
    change(x,y);  
    cout<<a<<endl;  
    cout<<b<<endl;  
    return 0;  
}  
void change(int& x,int& y){  
    int temp;  
    temp = x;  
    x = y;  
    y = temp;  

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;

void change(int& x,int& y);
int main(){
 int a = 10,b = 20;
 int& x = a;
 int& y = b;
 change(x,y);
 cout<<a<<endl;
 cout<<b<<endl;
 return 0;
}
void change(int& x,int& y){
 int temp;
 temp = x;
 x = y;
 y = temp;
}
传递地址代码(实参、形参都指向同一个对象,交换成功):
view plaincopy to clipboardprint?
#include "stdafx.h"  
#include <iostream>   
#include <time.h>  
using namespace std;  
 
void change(int *x,int *y);  
int main(){  
    int a = 10,b = 20;  
    int *x = &a;  
    int *y = &b;  
    change(x,y);  
    cout<<a<<endl;  
    cout<<b<<endl;  
    return 0;  
}  
void change(int *x,int *y){  
    int temp;  
    temp = *x;  
    *x = *y;  
    *y = temp;  

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;

void change(int *x,int *y);
int main(){
 int a = 10,b = 20;
 int *x = &a;
 int *y = &b;
 change(x,y);
 cout<<a<<endl;
 cout<<b<<endl;
 return 0;
}
void change(int *x,int *y){
 int temp;
 temp = *x;
 *x = *y;
 *y = temp;
}
值传递代码(实参、形参不是同一个对象,只是形参交换成功):
view plaincopy to clipboardprint?
#include "stdafx.h"  
#include <iostream>   
#include <time.h>  
using namespace std;  
 
void change(int x,int y);  
int main(){  
    int a = 10,b = 20;  
    change(a,b);  
    cout<<a<<endl;  
    cout<<b<<endl;  
    return 0;  
}  
void change(int x,int y){  
    int temp;  
    temp = x;  
    x = y;  
    y = temp;  

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;

void change(int x,int y);
int main(){
 int a = 10,b = 20;
 change(a,b);
 cout<<a<<endl;
 cout<<b<<endl;
 return 0;
}
void change(int x,int y){
 int temp;
 temp = x;
 x = y;
 y = temp;
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lihan6415151528/archive/2009/09/27/4600981.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值