博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ const总结
阅读量:6998 次
发布时间:2019-06-27

本文共 1091 字,大约阅读时间需要 3 分钟。

hot3.png

C++ const总结

const int a = 5;

对象a是个int型的const对象

int const b = 5;

跟上面相同,对象b也是个int型的const对象

 

const double *cptr;

cptris a pointer to a double that is const

cptr指向的对象是double类型的const对象

 

例如:

const double pi = 3.14;

const double *cptr = π

 

const int universe = 42;

const int *cpv = &universe;  //ok: cpv is const

Int *cpv = &universe; //error, universeis const and don’t fit common pointer

普通指针不能指向const对象。

 

double dval = 3.14;

const double *cptr;

cptr = &dval; //ok: but can’t changedval through cptr

const指针对象可以指向普通的对象,但是不能使用指针修改该普通对象。

原理:const类型的cptr指针不可能知道它所指向的对象是const对象还是普通对象,所以它对它所指向的所有对象都当成是const对象。Const指针可以被认为是“它们认为它们自己指向const对象的指针”

 

const float *p; //Pointer to const object

指向const对象的指针

 

int errNumb = 0;

int *const curErr = &errNumb; //curErris a constant pointer

*curErr=12;

const指针,从右往左念:curErr is a constant pointer to an object of type int.

任何给const指针重新指向新对象的做法都是错误的。不过,可以通过const指针修改对象的值。

 

总结:

const int *a; 或者 int const*b;  指向const对象的指针

int *const c;    const指针

星号在const右边时,为指向const对象的指针- pointer to const

星号在const左边时,为const指针- const pointer

 

 

转载于:https://my.oschina.net/u/923087/blog/279361

你可能感兴趣的文章