Home  >  Q&A  >  body text

c++ - 顶层const跟底层const有啥区别

怎么感觉顶层const跟底层const的意思都是定义了就不能改了。 比如 const in i =1; 跟 int const i =1;有啥区别

怪我咯怪我咯2764 days ago556

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 14:55:39

    There is no difference between int const i and const int i, they both mean i is a constant. The same goes for const int p and int const p, which means that p is a constant, but p is a variable; int const p is different from them, which means that p is a constant and *p is a variable.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:55:39

    The top-level const and the bottom-level const are mainly for pointers.
    The so-called top-level const refers to the immutability of the pointer, that is, the position pointed by the pointer remains unchanged! int *const p = &i; then the value of p will not change. Here you can change the value of i in other ways. For example, you can directly assign i = 9;. constThere’s nothing you can do about it.
    The underlying const means that the object pointed to by the pointer or the built-in type remains unchanged. const int *p = &i;The value of i here is not allowed to change, but you can still change p. For example, you can do this const int *p = &j;
    I understand that const is a convention, which means that if I use const, it will not change the value of the variable, and there is nothing I can do if others mess with it.
    Some simple opinions, please give me some advice.

    reply
    0
  • Cancelreply