声明:以下内容B站/Youtube学习笔记,https://www.youtube.com/user/BoQianTheProgrammer/ Advanced C++.
1 /* 2 why use const 3 a)Guards against inadvertent write to the variable 4 b)Self documenting 5 c)Enables compiler to do more optimization,making code tighter,faster 6 d)const means the variable can be put in ROM 7 */ 8 //const 9 // A compile time constraint that an object can not be modified 10 11 int main() 12 { 13 const int i = 9; 14 //i = 7; wrong 15 //如何修改i的值呢? 16 const_cast<int&>(i) = 7; 17 18 int j; 19 static_cast<const int&>(j) = 7;//wrong,此时j被转成const 20 21 const int *p1 = &i;//data is const,pointer is not 22 p1++; 23 int * const p2;//pointer is const,data is not 24 const int* const p3;//data and pointer are both const 25 26 int const *p4 = &i; 27 const int *p4 = &i; 28 //If const is on the left of *,data is const 29 //If const is on the right of *,pointer is const 30 }