声明指针时,可以在类型前或后使用关键字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成员函数 可以将关键字用于成员函数。例如: class Rectangle { pubilc: ..... void SetLength(int length){itslength = length;} int GetLength() const {return itslength;} //成员函数声明为常量 ..... private: int itslength; int itswidth; }; 当成员函数被声明为const时,如果试图修改对象的数据,编译器将视为错误。 如果声明了一个指向const对象的指针,则通过该指针只能调用const方法(成员函数)。 示例声明三个不同的Rectangle对象: Rectangle* pRect = new Rectangle; const Rectangle * pConstRect = new Rectangle; //指向const对象 Rectangle* const pConstPtr = new Rectangle; pConstRect是指向const对象的指针,它只能使用声明为const的成员函数,如GetLength()。
const this 指针 将对象说明为const时,相当于该对象的this指针声明为一个指向const对象的指针。const this指针只能用来调用const成员函数。
如果对象不应被修改,则按引用传递它时应使用const进行保护。 务必将指针设置为空,而不要让它未被初始化(悬浮) |
|