@@ -0,0 +1,46 @@
+//引用做函数的返回值
+
+//注意 : 不要返回局部变量引用
+//用法 : 函数调用作为左值
+#if(0)
+#include <iostream>
+int& test01()
+{
+ int a = 10; //局部变量存放在四区中的 栈区
+ return a;
+}
+int& test02()
+ static int a = 10; //静态变量存放在全局区 , 全局区上的数据在程序结束后由系统释放
+int main()
+ //int& ref = test01();
+ //std::cout << " ref = " << ref << std::endl; // 第一次结果正确 , 是因为编译器做了保留
+ //std::cout << " ref = " << ref << std::endl; // 第二次结果错误 , 是因为a的内存已经被释放
+ int& ref2 = test02();
+ std::cout << " ref2 = " << ref2 << std::endl;
+ test02() = 1000; //如果函数的返回值时引用,这个函数调用可以作为左值
+ system("pause");
+ return 0;
+#endif
@@ -0,0 +1,41 @@
+//引用的本质
+//本质 : 引用的本质在C++内部实现是一个指针常量
+//发现是引用,替换为 int* const ref = &a;
+void func(int& ref)
+ ref = 100; //ref是引用,转换为 *ref = 100
+ int a = 10;
+ //自动转换为 int* const ref = &a ; 指针常量是指针指向不可以更改,也说明为什么引用不可更改
+ int& ref = a;
+ ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;
+ std::cout << "a : " << a << std::endl;
+ std::cout << " ref : " << ref << std::endl;
+ func(a);
+//C++推荐引用技术,因为语法方便,引用本质是指针常量,但是左右的指针操作编译器都帮我们做了
+//常量引用
+//使用场景 :常量引用只要是用来修饰形参,防止误操作
+//在函数形参列表中,可以加const修饰形参,防止形参改变实参
+//打印数据的函数
+void showValue(const int &val)
+ //val = 1000;
+ std::cout << " val = " << val << std::endl;
+ //使用场景
+ //int& ref = 10; //引用必须引一块合法的内存空间
+ //加上const之后 编译器将代码修改为 int temp = 10; const int & ref = temp;
+ //const int& ref = 10; //引用必须引一块合法的内存空间
+ //ref = 20; // 加入const之后变为只读,不可以修改
+ //ref = 100; // 加入const后不可以修改变量
+ std::cout << ref << std::endl;
+ int a = 100;
+ showValue(a);
+ std::cout << " a = " << a << std::endl;