0
点赞
收藏
分享

微信扫一扫

c++函数三种传递方式

RJ_Hwang 2022-01-22 阅读 132

这里我会带大家了解c++中函数的三种传递方式

我们以swap(交换)函数为例:

int tem = a;
	a = b;
	b = tem;

第一种,值传递:

用形参接收实参的值进行操作,对实参没有影响

eg:

#include<iostream>
using namespace std;
void swap(int a,int b)
{
	int tem = a;
	a = b;
	b = tem;
}
int main()
{
	int a = 10;
	int b = 20;
	cout << "交换前" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	swap(a, b);
	cout << "交换后" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	system("pause");
	return 0;
}

 

第二种,地址传递: 

将实参的地址传过去,从而改变实参的值

#include<iostream>
using namespace std;
void swap(int* a,int* b)
{
	int tem = *a;
	*a = *b;
	*b = tem;
}
int main()
{
	int a = 10;
	int b = 20;
	cout << "交换前" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	swap(&a, &b);
	cout << "交换后" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	system("pause");
	return 0;
}

 

第三种,引用传递:

就我自身而言了,认为只是最简单的一种方式,实现实参的改变。

#include<iostream>
using namespace std;
void swap(int& a,int& b)
{
	int tem = a;
	a = b;
	b = tem;
}
int main()
{
	int a = 10;
	int b = 20;
	cout << "交换前" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	swap(a, b);
	cout << "交换后" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	system("pause");
	return 0;
}

 

希望能给与大家帮助。 

 

 

 

 

举报

相关推荐

0 条评论