传值,
是把实参的值赋值给行参
那么对行参的修改,不会影响实参的值
传地址 ,
是传值的一种特殊方式,只是他传递的是地址,不是普通的如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