**
指向对象的常指针和指向常对象的的指针基本用法和注意事项:
**
# include <iostream>
# include <string>
using namespace std;
class Time
{
public:
Time(int h = 10, int m = 30, int s = 59):hour(h), minter(m), sex(s){};
void out_value();
void set_value(int, int, int);
void fun(const Time *p); //使用指向常对象的指针作为形参,可以接收非const对象的实参也可接收const对象的实参
//即使接收的是非const对象,也可以防止其对象的值被修改,
//若传入的实参是const对象,则只能使用指向常对象的指针作为形参
int hour;
int minter;
int sex;
};
int main(void)
{
//指向对象的常指针:
/*
Time t1(10, 10, 10), t2;
Time * const p1 = &t1; //正确定义指向对象的常指针,p1始终指向t1
Time * const p1; //必须在p1初始化给予初值,否则p1会指向系统未分配的空间(是一个垃圾值)
p1 = &t1; //error:即在其初始化时将其指向一个对象,此后不可在改变
*/
//p1 = &t2;//error:p1是指向t1的常指针,不能改变使其指向t2
//指向常对象的指针:
Time t2(9, 9, 9), t3;
const Time * p2; //定义指向常对象的指针
p2 = &t2; //正确:p2可以指向非const的对象
//p2->hour = 12; //error:该对象中的数据成员不能通过p2来改变
//p2->set_value(10,10,11); //error:
//p2->out_value(); // 不能使用指向常对象的指针引用普通成员函数
t2.set_value(10,10,11); //正确:
t2.out_value(); // 可以使用原对象名引用普通成员函数
p2 = &t3; //正确:指向常对象的指针可以改变其指向的对象,即:可以改变p2中存储的地址,使其指向另一个对象
return 0;
}
void Time::set_value(int h, int m, int s)
{
hour = h;
this->hour = h;
(*this).hour = h;
minter = m;
sex = s;
}
void Time::out_value()
{
cout << hour << ":" << minter << ":" << sex << endl;
}