传值,传地址和传引用

#if(0)
#include <iostream>
void changeage(int age,int newage);
using namespace std;
int main(int argc, char *argv[])
{
	int age =24;
	
	cout <<"MY age is"<<age<<endl;
	changeage(age,age+1);
	
	cout<<"Now my age is"<<age <<endl;
	return 0;
}
void changeage(int age,int newage)
{
	age = newage;
	cout<<"In this , my age is"<<age<<endl;
}
/*
MY age is24
In this , my age is25
Now my age is24
请按任意键继续. . .
*/
#endif
#if(1)
#include <iostream>
void changeage(int *age,int newage);
using namespace std;
int main(int argc, char *argv[])
{
	int age =24;
	
	int *p;
	p= &age;
	cout <<"MY age is"<<age<<endl;
	changeage(p,age+1);
	
	cout<<"Now my age is"<<age <<endl;
	return 0;
}
void changeage(int *age,int newage)
{
	*age = newage;
	cout<<"In this , my age is"<<*age<<endl;
}
#endif

上面的输出 可以看出, 如果你要跨函数改变内存的值 ,那么需要传递的是地址 
 
黑羊眨眼黑羊
 
  1. 下面请看 swap函数的使用
  1: #if(1)
  5: int main(int argc, char *argv[])
  6: {
  7:   int x,y;
  8:   
  9:   cout <<"请输入两个不同的值";
 10:   cin>>x>>y;
 11:   
 12:   swap(&x,&y);
 13:   
 14:   cout<<"调换后输出:"<<x<<' '<<y<<endl;
 15:    
 16:   return 0;
 17: }
 18: 
 19: void swap(int *x,int *y)
 20: {
 21:   int temp;
 22:   temp =*x;
 23:   *x = *y;
 24:   *y  = temp;
 25: }
 26: 
 27: #endif
 28: 

另一种 不需要中介的 互换方案:swap2

提示 使用  异或 。

引用传递:传址在我们呢看来已经很不错了,不过c++语言的大神们在完善的过程中完善了地址这个概念

设想 如果事先就知道某个函数的参数只能接受一个地址,能不能使用某种约定使得调用该函数时

不需要使用指针的语法呢?

于是乎引用 传递方式传递输入方式的概念因此而产生了。

  1: #include <iostream>
  2: void swap(int &x,int &y);
//
  3: using namespace std;
  4: int main(int argc, char *argv[])
  5: {
  6: 	int x,y;	
  7: 	cout <<"请输入两个不同的值";
  8: 	cin>>x>>y;	
  9: 	swap(x,y);	
 10: 	cout<<"调换后输出:"<<x<<' '<<y<<endl;
 11: 	 
 12: 	return 0;
 13: }
 14: 
 15: void swap(int &x,int &y)
 16: {
 17: 	int temp;
 18: 	temp =x;
 19: 	x = y;
 20: 	y  = temp;
 21: }
posted @ 2013-02-28 22:08  搅着青春吹泡泡  阅读(166)  评论(0编辑  收藏  举报