const 详解

1、const int max = 100; 

定义const常量,不能修改max的值。

2、const int max = 100; int min = 10 ; 

    const int& ma = max; const int& mi = min;

    定义常量引用,不能通过引用修改变量的值, 所指向的变量可以不是const常量。

3、const int max = 100; int min = 10 ;

    const int* pMax = &max; const int* pMin = &min;  pMax = &min ;

    定义常量指针,不能通过指针修改变量的值,但可以修改指针所指向的地址,所指向的变量可以不是const常量。

    备:const int* pMax 和 intconst* pMax 一样

4、int max = 100;

   int * const pMax = &max; *pMax = 900 ;

    定义指针常量,指针pMax是常量,不能修改所指向的地址,但可以修改所指向变量的值。

5、int max = 100;

    const int* const pMax = &max

    定义指向常量的指针常量。即3和4的合体。

    备:注意指针常量与常量指针的区别,一个修饰指针本身,一个修饰指针所指向的变量。

6、constexpr和常量表达式

    常量表达式(const expression)是指值不会改变并且在编译过程中就能得到计算结果的表达式。

    C++11新标准规定,允许将变量声明为constexpr类型以便由编译器验证变量的值是否是一个常量表达式。

    主要const 和 constexpr的区别:

    const int *p = nullptr; 常量指针

    constexpr int * q = nullptr 指针常量。

7、void foo(const char* var)、void foo(const int& var)

    修饰参数表示函数体中不能修改参数的值。

8、const int foo()、 const int* foo()

    返回值是常量。

9、void foo() const

    修饰成员函数,表示不能修改成员变量,也不能调用类中任何非const成员函数。








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值