c++ key word const

1. const修饰变量

    const int a = 10; // declare a constant

    const int* pa;  // variable pa pointer points to a constant not correct, should be could not change the *pa by pa.

    int* const pb;  // constant pointer pb points to a variable

    const int* const pa; // constant pointer pc points to a constant

    int *pc = &a;     // error

    const int* pa = &a;  // ok

    const int &ra = a; // ok

    int &rb = a;  // error


confusion:


      int main()

      {

        const int a = 10;

        int *pa = (int *) &a;

        *pa = 11;

        printf("*pa = %d \n", *pa);

        printf("a =  %d\n", a);

        return 0;

       }

output:

       *pa = 11

       a = 10


but use gdb to check value, 

        *pa 11

          a  11

solved, 由于编译器优化,a 被存放到寄存器里面,解决方法 在前面加上volatile const int a. 或者关闭编译器优化选项。

why? could someone explain?

 

2. const parameter 不改变 parameter

    void print(const string s);

    string str("Hello  world")

    print(str);   // ok

3. const return value

    const get();

    prevent users to change the return value

4. const member function

    void ClassName::print(string s) const
   just use in member function, it indicates that the function doesn't change the member variable

   const and non-const function could overload 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值