1、常指针:将指针变量声明为const型,指针值始终保持为其初值,不能改变。
定义指向对象的常指针的一般形式为:
类名* const 变量名:指向对象的常指针。
常用用途:将一个指针固定地与一个对象联系
将常指针作为函数的形参,目的是不允许在函数执行过程中改变指针变量的值。
#include <iostream>
using namespace std;
class Time
{
private:
int hour;
int minute;
int sec;
public:
Time():hour(0),minute(0),sec(0){};
Time(int h,int m,int s):hour(h),minute(m),sec(s){};
void set_time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
void show_time() const
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
};
int main()
{
// Time t1(10,12,15),t2;
//
// Time* const pt=&t1;//pt是指向对象的常指针
//
// pt=&t2;//错误,pt应始终指向同一个对象
//Time t1(10,12,13);
//t1.show_time();
//t1.set_time(11,20,15);
//t1.show_time();
const Time t1(10,11,12);
t1.show_time();
/*t1.set_time(13,14,15);*/
return 0;
}
2、指向常变量的指针变量
指针变量的值本身可改变,指针指向的值不可改变。
定义指向常变量的指针变量的一般形式如下:
const 类名 *变量名 、、类名 const *变量名
int main()
{
const char c[]="hello";//常变量(字符常量)
const char* pt=c;//指向常变量的指针指向常变量
return 0;
}
如果一个变量已被声明为常对象、常变量,只能用指向常变量的指针、对象来指向,而不能用非const型指针来指向。