C++ 函数的引用传递

#include
#include
using namespace std;

//1、值传递
void mySwap01(int a, int b) {
	int temp = a;
	a = b;
	b = temp;

	cout << "mySwap01 a=" << a << endl;
	cout << "mySwap01 b=" << b << endl;

}

//2、地址传递
void mySwap02(int * a, int * b) {
	int temp = *a;
	*a = *b;
	*b = temp;

	cout << "mySwap01 a=" << *a << endl;
	cout << "mySwap01 b=" << *b << endl;

}

//3、引用传递
void mySwap03(int &a,int &b) {
	int temp = a;
	a = b;
	b = temp;

	cout << "mySwap03 a=" << a << endl;
	cout << "mySwap03 b=" << b << endl;
}

int main() {

	int a = 10;
	int b = 20;
	
		mySwap01(a,b);  //值传递,形参不会修饰实参

	//  mySwap02(&a, &b);

	//  mySwap03(a, b);

	cout << "a="<

值传递实参不会改变 

C++ 函数的引用传递_第1张图片

地址传递会改变实参的值 

C++ 函数的引用传递_第2张图片

 引用传递

C++ 函数的引用传递_第3张图片

你可能感兴趣的:(C++)