Home Article 引用的本质与常量引用

引用的本质与常量引用

Release time:2020-07-24 20:08:50 Author:admin Reading volume:61
  1. 引用的本质
#include <iostream>
using namespace std;
//引用的本质在C++内部实现是一个指针常量
//发现是引用,转换为int * const ref = &a;
void func(int &ref)
{
    ref = 100;
    //ref是引用,转换为*ref = 100
}
int main()
{
    int a = 10;
    //自动转化为int* const ref = &a;
    //指针常量是指针指向不可更改,所以引用不可更改
    int& ref = a;
    ref = 20;
    //内部发现ref是引用,自动转化成*ref = 20;
    cout << "a=" << a  << endl;
    cout << "ref=" << ref << endl;
 
    func(a);
    cout << "ref=" << ref << endl;
    return 0;
}

2.常量引用
#include <iostream>
using namespace std;
//常量引用:修饰形参防止误操作
 
void show(const int & val)//加const以后就不能修改数据
{
    cout << "val = " << val << endl;
    //val = 1000;//数据会被修改,const后不可修改
    cout << "val = " << val << endl;
 
}
int main()
{
    int a  =10;
    //int &ref = 10;//不允许,必须用合法的内存空间
    const int & ref = 10;
    // 加const以后,
    // 编译器将代码修改为int temp = 10;
    // const int & ref = temp;
    //ref = 20;//const 以后就不可以修改,只读
 
    int b = 100;
    show(b);//b = 100;
    cout << "b =" << a << endl;// a= 1000;加const以后就不可以修改
 
    return 0;
}
 
支付宝打赏 微信打赏
  
I want to comment

Search

Leave a message
http://blog.rjxj513.com/
User login
You have not written any reviews yet!
You have commented!
Can only praise once!
You have a collection!