5、引用的本质.cpp 680 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //引用的本质
  2. //本质 : 引用的本质在C++内部实现是一个指针常量
  3. #if(0)
  4. #include <iostream>
  5. //发现是引用,替换为 int* const ref = &a;
  6. void func(int& ref)
  7. {
  8. ref = 100; //ref是引用,转换为 *ref = 100
  9. }
  10. int main()
  11. {
  12. int a = 10;
  13. //自动转换为 int* const ref = &a ; 指针常量是指针指向不可以更改,也说明为什么引用不可更改
  14. int& ref = a;
  15. ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;
  16. std::cout << "a : " << a << std::endl;
  17. std::cout << " ref : " << ref << std::endl;
  18. func(a);
  19. system("pause");
  20. return 0;
  21. }
  22. //C++推荐引用技术,因为语法方便,引用本质是指针常量,但是左右的指针操作编译器都帮我们做了
  23. #endif