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()
{
}
{
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()
{
}
相关文章推荐
- 说明以下关键字的作用 auto static register const volatile extern
- C语言中Static和Const关键字的的作用
- C语言const关键字作用
- static和const关键字的作用
- const作用总结
- static和const关键字的作用
- const 和 static 的作用
- C语言中关键字auto、static、register、const、volatile、extern的作用
- c++中const的作用
- 关键字static、const、volatile的作用
- 类声明中const 的作用
- [老转]c++中const的作用
- const在c++中的作用
- 关键字static 与const的作用及区别
- static、const和volatile的作用
- const的作用
- static和const的作用
- C/C++关键字const作用总结
- CONST的主要作用
- 关键字 const 的作用(面试)