#define _CRT_SECURY_NO_WARNINGS
#include <iostream>
using namespace std;
//1、值传递 不改变原始值
void mySwap01(int a,int b)
{
int tmp = a;
a = b;
b = tmp;
}
//2、地址传递 改变原始值
void mySwap02(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
//引用传递 相当于地址传递
void mySwap03(int& a, int& b)
{
int tmp = a;
a = b;
b = tmp;
}
/*引用的注意事项 */
//A:引用必须引一段合法的内存空间
//B:不要返回局部变量的引用
//C: 如果函数的返回值是引用 该函数可以作为引用的左值
int main()
{
int a = 10, b = 20;
mySwap01(a, b);
cout << "a=" << a << " b=" << b << endl;
mySwap02(&a, &b);
cout << "a=" << a << " b=" << b << endl;
mySwap03(a, b);//相当于int &a = a; int &b = b;
cout << "a=" << a << " b=" << b << endl;
system("pause");
return EXIT_SUCCESS;
}
C++基础学习DAY1-09 参数的传递方式
最新推荐文章于 2024-06-12 16:46:27 发布