gpt4 book ai didi

c++ 指针传参 学习笔记

转载 作者:知者 更新时间:2024-03-13 02:03:37 26 4
gpt4 key购买 nike

swap1 失败,swap2和swap3成功,

swap3最方便。

void swap1(int a, int b);
void swap2(int *p1, int *p2);
void swap3(int &r1, int &r2);

//直接传递参数内容
void swap1(int a, int b) {
	int temp = a;
	a = b;
	b = temp;
}

//传递指针
void swap2(int *p1, int *p2) {
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}

//按引用传参
void swap3(int &r1, int &r2) {
	int temp = r1;
	r1 = r2;
	r2 = temp;
}

int main()
{
	int num1, num2;
	num1 = 5;
	num2 = 10;
	swap1(num1, num2);
	cout << num1 << " " << num2 << endl;    //输出与输入相同,因为值传递,不能改变原始数据

	swap2(&num1, &num2);
	cout << num1 << " " << num2 << endl;    //输出与输入相反,指针传递可以改变原始数据

	swap3(num1, num2);
	cout << num1 << " " << num2 << endl;     //输出与输入相反,因为引用传递,可以改变原始数据

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com