#include<iostream>
using namespace std;
//交换函数
//1.值传递
void swap01(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
//2.地址传递
void swap02(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
//3.引用传递
void swap03(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 10;
int b = 20;
swap01(a,b);//值传递,形参不会修饰实参
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "----------------------" << endl;
swap02(&a,&b);//地址传递 形参会修饰实参
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "----------------------" << endl;
//在执行swap03时a b的值在swap02中完成了交换
swap03(a,b); //引用传递 形参也会修饰实参
cout << "a= " << a << endl; //10
cout << "b= " << b << endl; //20
}
c++的值传递 地址传递 引用传递
最新推荐文章于 2023-10-05 22:42:33 发布