C++中CONST的用法
来源:优易学  2011-12-2 10:03:23   【优易学:中国教育考试门户网】   资料下载   IT书店
  IBM的一道关于CONST的笔试题看得我很是晕啊,题目是这样的:
  const char *const * keywords
  const char const * keywords
  const char *const keywords
  const char const keywords
  下面总结一下CONST的用法。const主要是为了程序的健壮型,减少程序出错。青年人网提示const指针和引用一般用在函数的参数中。最基本的用法如下:
  // a的内容不变,a只能是100也就是声明一个int类型的常量(#define b =100)
  const int a=100;
  int const b=100; //和上面作用一样
  //下面两句话一样
  const int b=100;
  int const b=100;
  const放在*左侧修饰的是指针的内容,const放在*右侧修饰的是指针本身。如下:
  const int* pa = &a; //指针指向的内容为常量(就是a的值不变)
  int const *a = &b; //指针指向的内容为常量(就是b的值不变)*p=3//error
  int* const a = &b; //指针为常量,不能更改指针了如 a++但可以改值*a=3;
  const int* const a = &b,其中a是一个指向常量的常指针,一般用来传递多维数组,使用方法如下:
  char* init[] = {"Paris","in the","Spring"};
  void fun(const int* const a){}
  fun(init)//保护参数不被修改
  CONST的主要功能就是保护函数的参数,使其在调用时不被修改:
  int A(int)const; //是常函数,只能用在类中,调用它的对象不能改改变成员值
  const int A(); //返回的是常量,所以必须这么调用 cosnt int a=A();
  int A(const int); //参数不能改值,可用在任意函数
  int height() const;//常函数只能由常函数调用
  int max(int,int) const;
  int Max = max(height(),height());
  因此上面的问题迎刃而解了。const放在*左侧修饰的是指针的内容,const放在*右侧修饰的是指针本身。
  const char *const * keywords ----keywords 是一个普通的指针,它指向一个指向常量的常量指针
  const char const * keywords ----与const char *keywords 或char const *keywords 等同,keywords是指向常量的普通指针
  const char *const keywords ----keywords是指向常量的常量指针,无论是它的值还是它指向的地址空间的值都不能更改
  const char const keywords ----与const char keywords 或 char const keywords等同, 定义了一个字符常量keywords 。

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训