C++中const的详细解释

原文网址:http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-int-const

Read it backwards...

  • int* - pointer to int
  • int const * - pointer to const int
  • int * const - const pointer to int
  • int const * const - const pointer to const int

Now the first const can be on either side of the type so:

  • const int * == int const *
  • const int * const == int const * const

If you want to go really crazy you can do things like this:

  • int ** - pointer to pointer to int
  • int ** const - a const pointer to a pointer to an int
  • int * const * - a pointer to a const pointer to an int
  • int const ** - a pointer to a pointer to a const int
  • int * const * const - a const pointer to a const pointer to an int
  • ...

And to make sure we are clear on the meaning of const

const int* foo;
int *const bar; //note, you actually need to set the pointer 
                //here because you can't change it later ;)

foo is a variable pointer to a constant int. That is you change what you point to but not the value that you point to. Most often this is seen with cstrings where you have a pointer to a const char. You may change which string you point to but you can't changed the strings content. This is important when the string itself is in the data segment of a program and shouldn't be changed.

bar is a const or fixed pointer to a value that can be changed. This is like a reference with out the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow null pointers.

=================================================================

typedef char *ASTRING;
const ASTRING astring;

The type of astring is char * const, not const char *. This is one reason I always tend to put const to the right of the type, and never at the start.

更详细版本:http://www.parashift.com/c++-faq-lite/overview-const.html---C++ const百科全书。。

http://duramecho.com/ComputerInformation/WhyHowCppConst.html,const详解

http://www.cprogramming.com/tutorial/const_correctness.html,专家博客解释const

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值