您的位置:首页 > 其它

const 的作用

2007-03-25 18:50 78 查看
void main()
{
int i = 1,j = 2;
const int csti = 3;
const int* cstpi = &i; //指向常量的指针
int *const pcsti = &i; //常量指针
const int *const pcstpi = &i; //指向常量的常指针

csti = i; //错误,非常量不可以给常量赋值

cstpi = 2; //错误,指针所指的内容是常量
cstpi = &j; //正确,可以修改指针的指向

*pcsti = 2; //正确,指针所指的内容不是常量
pcsti = &j; //错误,指针不可以修改

*pcstpi = 2; //这两个都错误,因为这里
pcstpi = &j; //指针所指的内容是常量,而且指针也是常量
}

常量限定,可以加强程序的健壮性
例如当一变量地址传递时,不可以修改对其进行修改
加上const就可以解决问题

class A
{
public:
int x,y;
A(int x,int y)
{
this->x = x;
this->y = y;
}
};
void Fun()const
{
A a(4,5);
a.x = 3; //错误,不可以对对象进行修改
}
void main()
{
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: