理解const

来源:互联网 发布:孕期软件下载 编辑:程序博客网 时间:2024/05/16 01:43

看了挺多中文关于const使用的文章,还是有点懵懵懂懂,直到看到这篇英文文章,豁然开朗,看来以后还是要多看看老外写的东西。

 

理解const 使用,总结为一句话:from right to left!

 

1、  const int * & i

From right to left:"i is a reference to a pointer to a constant int".
Except I've broken my right to left rule here byreading the tokens in
the order
See below for the explanation, after your thirdexample.

 

2、  int * const &i

"i is a referenceto a constant pointer to an int

 

3、   int const *& 

Right to left again:"i is a reference to a pointer to a constant
int". Now that's exactly the same as thefirst one. What I think is
confusing you is this - leaving pointers andreferences out of it, are
you aware that

const int i;
and
int const i;

both mean the same thing? The only difference isthat the second one
makes sense reading from right to left ("i isa constant int"). For
this reason some people prefer to always put thetype before the
const. Whenever const and a type name (int in yourexamples) appear
next to each other they can appear in eitherorder. So

const int * & i;
int const * & i;

both mean "i is a reference to a pointer to aconstant int".

 

4、  const int * const &i

const int * const &i;
"i is a reference to a constant pointer to aconstant integer".
This could also be written
int const * const & i;
which reads better right to left.

 

5、  const int const * & i;

"i is a referenceto a pointer to a ... errrm constant int constant
???" What's a constant int constant? Removeone of the consts and you
have either
int const * & i;
or
const int * & i;
which we've seen above both mean the same thing.Since both occurances
of const in your declaration would do the samething if the other
const wasn't there, you are getting a messageabout duplicate const.

 

example1:

 

the result:200

 

example2:

 

 

example3:

 

int * const i // i is a constant pointer

cont int * i // i is a pointer to a constant int  

from right to left 

a constant pointer that is to say the pointer is not allow to change