原文地址:http://www.cnblogs.com/frustrate2/archive/2013/01/12/2857434.html
指向const的指针和const指针
声明指针时,可以在类型前或后使用关键字const,也可在两个位置都使用。例如,下面都是合法的声明,但是含义大不同:
const int * pOne; //指向整形常量 的指针,它指向的值不能修改
int * const pTwo; //指向整形的常量指针 ,它不能在指向别的变量,但指向(变量)的值可以修改。
const int *const pThree; //指向整形常量 的常量指针 。它既不能再指向别的常量,指向的值也不能修改。
理解这些声明的技巧在于,查看关键字const右边来确定什么被声明为常量 ,如果该关键字的右边是类型,则值是常量;如果关键字的右边是指针变量,则指针本身是常量。下面的代码有助于说明这一点:
const int *p1; //the int pointed to is constant
int * const p2; // p2 is constant, it can't point to anything else
const成员函数、指向const对象的指针和指向对象的const指针
可以将关键字用于成员函数。例如:
class Rectangle
{
pubilc:
.....
void SetLength(int length){itslength = length;}
int GetLength() const {return itslength;} //成员函数声明为常量
.....
private:
int itslength;
int itswidth;
};
当成员函数被声明为const时,如果试图修改对象的数据,编译器将视为错误。
如果声明了一个指向const对象的指针,则通过该指针只能调用const方法(成员函数)。
const Rectangle * pConstRect = new Rectangle; //指向const对象
pConstRect是指向const对象的指针,它只能使用声明为const的成员函数,如GetLength()。
Rectangle* const pConstPtr = new Rectangle;
指针的指向不能更改
其他const使用注意
见《高质量C++编程指南》11.1章
链接:http://man.chinaunix.net/develop/c&c++/c/c.htm#_Toc520634061