指针的const有两种:const修饰指针正指向的对象,或者修饰指针里面存储的地址。
/**
* 书本:【ThinkingInC++】
* 功能:const的传递和返回地址
* 时间:2014年9月7日14:11:41
* 作者:cutter_point
*/
//参数为非const类型的
void t(int*){}
//参数是const类型的
void u(const int* cip)//cip是一个指针,指向const的int数据
{
//! *cip=2; //非法操作,由于cip指向的值是被const修饰的,无法改变
int i=*cip; //拷贝数值,OK
//! int* ip2=cip; //非法操作,不能把const数据赋值给非const类型的
}
//返回const类型的指针地址
const char* v()
{
return "cutter_point--char* v()";
}
//返回const地址且const值的类型
const int* const w()
{
static int i;
return &i;
}
int main()
{
int x=0;
int* ip=&x;
const int* cip=&x;
t(ip);
//! t(cip); //不能把const的数据当参数赋值给非const的函数
u(ip);
u(cip); //由于是参数拷贝机制,所以const的参数可给const类型和非const类型
/*
如果传递或返回一个地址(一个指针或一个引用),客户程序员去取地址并修改其初值是
可能的。如果使这个指针或引用成为const,就会阻止这类事的发生,地址const返回
就是返回一个const指针就不能赋值给非const
*/
//! char* cp=v(); //函数v()的返回值只可以被赋给一个const指针,指针的值是const
const char* ccp=v();
//! int* ip2=w(); //w()的返回值是const的
const int* const ccip=w();
const int* cip2=w(); //这个也是可以,我也是醉了,C++果然神秘莫测
return 0;
}