const reference const

const(一)

const修饰的各种类型的变量后(包括普通变量,指针,类,结构体结构体的指针),其初始化的值不可更改

#include <iostream>
using namespace std;
//声明 一个结构体Student
struct Student{
     int num;
};
int main(int argc, char *argv[])
{ const float pi=3.14;  // 用const定义常量pi
    cout<<"pi的值 "<<pi<<endl;
  const struct Student stu={1};
    cout<<"stu.num的值 "<<stu.num<<endl;
  const struct Student stua={3};
  const struct Student stub={4};
    cout<<"stua.num的值 "<<stua.num<<endl;
    cout<<"stub.num的值 "<<stub.num<<endl;

 struct Student stuc;
 stuc.num=20;
 const struct Student *pstuc=&stuc;
 cout << "stuc.num is " << stuc.num <<endl;
 cout << "*pstuc.num is " << (*pstuc).num <<endl;
    return 0;
}

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{ int b=2;
  int a=1;
  const int *pa=&a;
             pa=&b;
    cout<<"pa的值  "<<pa<<endl;
    cout<<"a的地址 "<<&a<<endl;
    cout<<"b的地址 "<<&b<<endl;

        int const *pb = &a;
   cout<<"const int *pa = &a;这句含义一样"<<endl;

        int *const  pc=&a;
            *pc=3;
    cout<<"pc的值  "<<pc<<endl;
    cout<<"a的值  "<<a<<endl;

    //第一个const修饰*,所以*pe是常量
    //第二个const修饰pd,所以pd是常量
     const int * const pd = &a;
     int const * const pe = &a;
    //和const int * const pd = &a;含义一样
    return 0;
}

#include <iostream>
using namespace std;
 struct Student{
   int num;    };

int main(int argc, char *argv[])
{ struct Student stua={1};
  struct Student stub={2};

     struct Student * const pstua = &stua;//pstu是常量
const struct Student *pstub = &stub;

    cout<<"pstua的值  "<<pstua<<endl;
    cout<<"stua的地址 "<<&stua<<endl;
     cout<<"pstub的值  "<<pstub<<endl;
     cout<<"stub的地址 "<<&stub<<endl;
    return 0;
}

常引用(const reference)

当然还有刚见过的引用这个数据类型,所以也就有常引用这种东西了
我们类比指针的const修饰来说明常引用的性质

#include <iostream>
using namespace std;

int main(){
    int a = 1;
    //const int *pa = &a; *pa不能修改
    //也就是pa储存的地址对应的变量的值不能改,但是储存地址可以改
    
    //int * const pa = &a; pa不能修改
    //也就是pa储存的地址对应的变量的值可以改,但是储存地址不能变
    //同样的
    
    int b = 1;
    const int &rb = b;
    //rb的值不能改变也就是b的值不能通过rb改变
    //rb = 3;这句代码就是非法的
    
    //int & const ra = a; 等价于 int &ra = a;
    //这句话其实是废话,本来ra对应的被引用变量就不能换
    //所以我这里编译器对这句话报错了,错误如下
    //error: 'const' qualifiers cannot be applied to 'int&'
    
    getchar();
    return 0;
}
 

面有几种const引用的特性

引用可以修饰常量
#include <iostream>
using namespace std;

int main(){
    int a = 1;
    //int &r = 3;这种代码一看就是错的
    //但是const修饰之后就可以正常编译
    const int &ra = 3;
    cout << "ra is "<< ra << endl;
    
    getchar();
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值