开发者

What is the differnce between "const X a" and "X const a" if X is the class

i have a class name X, what is the d开发者_如何学编程ifference between "const X a" and "X const a"


Nothing.

A const qualifier applies to whatever is immediately to its left. If there is nothing to its left then it applies to whatever is immediately to its right.


In this case, there's no difference at all.

When you have a pointer or a reference, a change that might look almost the same is significant though. Given something like:

T * a;

The position of const (or volatile) relative to the asterisk is significant:

T const * a;
T * const a;

The first one says that a is a pointer to a const T (i.e., you can't modify the T object that a refers to). The second one says that a is a const point to a (non-const) T -- i.e., you can modify what a points at, but you can't modify the pointer itself, so you can't point it at a different object. Of course, you can also do both:

T const * const a;

This means you can't change the pointer itself or the T object it refers to.


If you use simple types (embedded or custom) then that is a matter of taste.

In case of using pointers there is a simple general rule: if const is placed before '*' then the data pointed is constant and otherwise the pointer itself is constant, you can't change its value.

For example:

const int  a=1;  // 'a' value can't be changed
const int* q;    // the data that 'a' point to is constant
int const* q;    // the same
int* const p=&a; // the pointer is constant: const is behind '*'

so

int b=2;
p = &b; // error: trying to change constant pointer
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜