C++的const变量

关于const的一些理解

1. 常变量

申明一个常变量的时候必须理解给他初始化,不然后续就不能给该变量进行初始化,而且还会报错,比如如下代码。

const int t;
t = 0;

出错信息

testConst.cpp:24:12: error: uninitialized const ‘t’ [-fpermissive]
  const int t;
            ^
testConst.cpp:25:4: error: assignment of read-only variable ‘t’
  t = 0;
2. 常引用

声明一个常引用也需要直接初始化,不然会报错。在引用初始化之后就不能更改引用的变量。但是 可以改变引用变量的值,如下

int a=0;
const int &t=a;
cout << t << endl;
a = 2;
cout << t << endl;  

输出就为

0
2
3. 常指针

话不多说,直接上代码

▸   int a = 2;                                                                             
▸   const int *t=&a;  // 常指针,指向的地址可以改变,但是不能改变该地址的值
▸   cout << *t << endl;
▸   a = 3;
▸   cout << *t << endl;

▸   // *t = 5; // 出错error: assignment of read-only location ‘* t’

▸   int b=4;;
▸   t = &b; 
▸   cout << *t << endl;

▸   int * const t1 = &a;  // 指针常量,这个和常引用类似,不能改变指针的指向,但是可以改变指
向地址的值
▸   cout << *t1 << endl;
▸   *t1 = 6;
▸   cout << *t1 << endl;
▸   a = 7;
▸   cout << *t1 << endl;
▸   // t1 = &b;  // 出错 error: assignment of read-only variable ‘t1’
▸   //
▸   const int* const t2 = &a;  // 常指针常量,包含上面两个特性
▸   cout << *t2 << endl;
▸   a = 8;
▸   cout << *t2 << endl;
▸   // t2 = &b; // 出错error: assignment of read-only variable ‘t2’
▸   // *t2 = 9;  // 出错error: assignment of read-only location ‘*(const int*)t2’

记忆方法const int *常指针,常量加在int上的,所以可以改变指向。int * const,指针常量,指针加在常量加在*上,所以是指针常量。

4. 常函数

常函数是针对类的成员函数的,常函数中 只能调用常成员函数,否则会出错

代码原型:

class B { 
▸   public:
▸   ▸   void test1() const {}
▸   ▸   void test2() const {
▸   ▸   ▸   A* t = new A;
▸   ▸   ▸   test3();
▸   ▸   ▸   test1();
▸   ▸   }
▸   ▸   void test3()  {}
};  

出错信息

testConst.cpp:17:10: error: passing ‘const B’ as ‘this’ argument discards qualifiers [-fpermissive]
    test3();
          ^
testConst.cpp:20:8: note:   in call to ‘void B::test3()’
   void test3()  {}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值