const指针:使用带有指针的const的注意事项来源: 发布时间:星期六, 2008年12月6日 浏览:73次 评论:0
当使用带有指针的const是,有两种选择:const修饰指针正指向的对象,或者const修饰在指针里存储的地址。这些语法容易使人混淆,但实践之后就好了。
1.指向const的指针 const int* u; u是一个指针,它指向一个const int,这里不需要初始化,因为u可以指向任何标识符(也就是说,它不是一个const),但它所指的值是不能被改变的。 对于 int const* u; 其效果与上面的定义完全一样,u是一个指向恰好是const的int的普通指针。但第一种可读性更强。 2.const指针 使指针本身成为一个const指针,必须把const标明的部分放在*的右边,如: int d = 1; int* const w = &d; w是一个指针,这个指针是指向int的const指针。因为指针本身现在是const指针,编译器要求给它一个初始值,这个值在指针生命期内不变。然而要改变它所指向的值是可以的,可以写 *w = 2; 可以使用下面两种合法形式中的任何一种把一个const指针指向一个const对象: int d = 1; const int* const x = &d; int const* const x = &d; 现在,指针和对象都不能改变。 测试一下: #include <iostream> using namespace std; int main() { int a = 1; int b = 2; const int* u; u = &a; //*u = 4; //非法 cout<<*u<<endl; int* const v = &b; //v = &a; //非法 *v = 6; cout<<b<<endl; int d = 1; const int* const x = &d; int const* const x2 = &d; return 0; } 0
相关文章
读者评论
发表评论 |