参数的传递方式 值传递地址传递引用传递 注意事项 引用必须引一块合法内存空间不要返回局部变量的引用当函数返回值是引用时候,那么函数的调用可以作为左值进行运算 指针的引用 利用引用可以简化指针可以直接用同级指针的 引用 给同级指针分配空间 常量的引用 const int &ref = 10;// 加了const之后, 相当于写成 int temp = 10; const int &ref = temp;常量引用的使用场景 修饰函数中的形参,防止误操作 登录后复制 #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; //1、值传递 void mySwap01(int a , int b) { int temp = a; a = b; b = temp; /*cout << ":::a = " << a << endl; cout << ":::b = " << b << endl;*/ } //2、地址传递 void mySwap02(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } //3、引用传递 void mySwap03(int &a , int &b) // int &a = a; int &b = b; { int temp = a; a = b; b = temp; } void test01() { int a = 10; int b = 20; //mySwap01(a, b); //mySwap02(&a, &b); mySwap03(a, b); cout << "a = " << a << endl; cout << "b = " << b << endl; } int& func() { int a = 10; return a; } //引用注意事项 void test02() { //1、引用必须引一块合法内存空间 //int &a = 10; //2、不要返回局部变量的引用 int &ref = func(); cout << "ref = " << ref << endl; cout << "ref = " << ref << endl; } int& func2() { static int a = 10; return a; } void test03() { int &ref = func2(); cout << "ref = " << ref << endl; cout << "ref = " << ref << endl; cout << "ref = " << ref << endl; cout << "ref = " << ref << endl; //当函数返回值是引用,那么函数的调用可以作为左值 func2() = 1000; cout << "ref = " << ref << endl; } int main(){ //test01(); //test02(); test03(); system("pause"); return EXIT_SUCCESS; } 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94. 原创作者: zaishu 转载于: https://blog.51cto.com/zaishu/11898245