0
点赞
收藏
分享

微信扫一扫

第二节 C++中的引用

进击的包籽 2022-04-30 阅读 30

2引用

2.1 引用的基本使用

语法:数据类型 &别名 = 原名

#include <iostream>
#include <string>


using namespace std;

int main()
{
   //引用的基本语法:数据类型 &别名 = 原名
   int a = 3;
   int &b = a;
   b = 20;

   //结果a = 20
   cout << a << endl; 


   system("pause");

   return 0;
}

2.2 引用的注意事项

  • 引用必须呀初始化
  • 引用一旦初始化后,就不能更改了
   int a = 3;
   int &b = a;
   //引用必须要初始化 例如int &b;这是错误的,这就代表没有初始化
   int c = 10;

   b = c ;  
   //这个只是赋值操作,并不是引用更改了,所以初始化过后就不能更改了

2.3 引用做函数参数

        作用:函数传参数时,可以利用引用的技术让形参修饰实参

        优点:可以简化指针修改实参

#include <iostream>
#include <string>

using namespace std;

//值传递函数
void MyTest01(int a, int b)
{
   int temp;
   temp = a;
   a = b;
   b = temp;

}
//地址传递函数
void MyTest02(int *a, int *b)
{
   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
}

//引用传递函数函数
void MyTest03(int &a, int &b)
{
   int temp;
   temp = a;
   a = b;
   b = temp;

}

int main()
{
   int a = 10;
   int b = 20;

   //值传递函数并不会替换a和b的值
   MyTest01(a, b);
   cout << " a = " << a << endl;
   cout << " b = " << b << endl;

   //地址传递可以改变a和b的值
   MyTest02(&a, &b);
   cout << " a = " << a << endl;
   cout << " b = " << b << endl;

   //引用函数会替换a和b的值,形参修饰实参
   MyTest03(a, b);
   cout << " a = " << a << endl;
   cout << " b = " << b << endl;

   system("pause");

   return 0;
}

2.4 引用做函数返回值

        作用:引用是可以作为函数的返回值存在的

        注意:不要返回局部变量的引用

        用法:函数调用作为左值

#include <iostream>
#include <string>

using namespace std;

//不要返回局部变量,在这个函数结束的时候局部变量就已经释放了,返回的别名对应的地址就相当于没有赋初值
int & MyTest01()
{
   int a = 10;

   return a;

}
//可以作为左值
int & MyTest02()
{
   static int a = 10;   //静态变量存放在全局区,在程序全部结束才会释放,所以这个返回就是可以的

   return a;

}
int main()
{
 
   int &ref = MyTest01();

   cout << ref << endl;
   cout << ref << endl;

   int &ref2 = MyTest02();

   cout << ref2 << endl;
   cout << ref2 << endl;
   //作为左值,这个函数返回的就是a的引用,赋值1000也是可以的
   MyTest02() = 1000;

   cout << ref2 << endl;
   cout << ref2 << endl;



   system("pause");

   return 0;
}

2.5 引用的本质

        本质:引用的本质在C++内部实现一个指针常量(int * constant a)

#include <iostream>
#include <string>

using namespace std;



void MyTest01(int & ref)
{
   ref = 100;   //  ref是引用,转化为*ref = 100

  

}
int main()
{
 
   int a = 10;
   
   //自动转换为int * const ref = &a;指针常量是指针指向不变,指向对应的值可以改变,也可以说明为什么引用不可更改
   int &ref = a;

   ref = 20;   //  内部发现ref是引用,转化为*ref = 20
   system("pause");

   return 0;
}

2.6 常量引用

        作用:常量引用主要用来修饰形参,防止误操作

        在函数形参列表中,可以加const修饰形参,防止形参改变实参

#include <iostream>
#include <string>

using namespace std;
void ShowValue(const int &a)
{
  //a = 20 这个是错的,const修饰的引用,在这个函数里面就不能再改变了,所以作用就是防止误操作形参从而改变实参

  cout << a << endl;

}
int main()
{
  //int &ref = 10;引用的本身需要一段合法的内存空间,因此这行错误
  //加入const就行了,编译器会优化代码,int temp = 10;const int &ref = temp;
  const int &ref = 10;        //这里ref不能再更改了,因为const int &ref-> const int * const ref(常量指针常量,不能修改地址和值,就只能读)


  //函数中利用常量引用防止误操作实参
  int a = 10;
  ShowValue(a);


   system("pause");

   return 0;
}

举报

相关推荐

0 条评论