// 指针常量和常量指针 // 1)指针常量可以通过指针改变变量的值 Int x = 2 ; Int * const point = & x; * point = 4 ; // now x = 4 void main() ... { char * const str = "china"; *str = "yangzhou"; // right 可以修改字符串的内容 str = "another"; // wrong } // 2)常量指针不可以 Int x = 2 ; Const int * point = & x; * point = 4 ; // wrong void main() ... { const char * str = "china"; *str = "yangzhou"; // wrong str = "another"; // right 修改指针指向另一个字符串 } // 3)上面两个例子看起来头疼吧,教你一个好方法; // 指针常量中,const用来修饰str,故str不能改变; // 常量指针中,const用来修饰*str,故*str不能改变。 // 4)两种方法的组合,使地址和内容都无法改变 void main() ... { const char * const str = "china"; *str = "yangzhou"; //wrong str = "another"; //wrong } // 5)const修饰“引用”,使“引用”不可修改。 void main() ... { int x = 20; const int &rx = x; rx = 2000; //wrong } // 6)声明函数时若在末尾加const,表示在该成员函数内不得改变类变量 class myclass ... { char * str; myclass() ...{ str = new char[64]; } ~myclass() ...{} char fun(char nstr) const ...{ str = "china";//wrong return str; } } // 7)数据传递给函数的方式默认是值传递,但如果一个函数被调用的次数过多,那就会 // 产生很多个拷贝,造成效率不高,故我们可以使用“引用”,但“引用”带来的隐患是它可 // 能修改变量的值,为此,我们可以使用“const引用”,使“引用”不可修改 int ReturnInt( const int & ); void main() ... { int i=10; ReturnInt(i); } int ReturnInt( const int & nInt) ... { nInt++;//wrong return nInt; }