C++ 传址 传值 传引用

/*
	C++  在默认情况下
	参数只能以 值 传递的方式给函数 

	被传递到函数的只是 变量的 值,
	永远不会是 变量的本身
	
	取址:获取某个变量的地址
	只需要在它的前面加上一个“取地址”
	& 就可以
	
	 注:
	 如果传过去的是地址,在函数中
	 必须要通过 “* ”进行解引用 
	 除非你有其他用途 

	引用传递: 传输地址 不用指针 
*/

//取值 
//#include <iostream>
//using namespace std;
//void swap(int *x,int *y);
//int main()
//{
    
    
//	int x,y;
//	cout << "请输入两个不同的值:";
//	cin >> x>>y;
//	
//	swap(&x,&y);
//	
//	cout << "调换后输出:"<<x<<' '<<y<<"\n\n";
//} 
//
//void swap(int *x,int *y)
//{
    
    
	int temp;
	temp=*x;
	*x=*y;
	*y=temp;
//	
//	//不需要转换
//	//^  相同为零 不同为1 
//	*x^=*y;
//	*y^=*x;
//	*x^=*y; 
//}


//引用传递
#include <iostream>
using namespace std;
void swap(int &x,int &y);
int main()
{
    
    
	int x,y;
	cout << "请输入两个不同的值:";
	cin >> x>>y;
	
	//要啥变换啥 
	swap(x,y);
	
	cout << "调换后输出:"<<x<<' '<<y<<"\n\n";
} 

//声明我用地址 
void swap(int &x,int &y)
{
    
    
//	int temp;
//	temp=x;
//	x=y;
//	y=temp;
	
	//不需要转换
	//^  相同为零 不同为1 
	x^=y;
	y^=x;
	x^=y; 
} 




猜你喜欢

转载自blog.csdn.net/qq_48167493/article/details/120645141