• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
BeyondTechnology
博客园    首页    新随笔    联系   管理    订阅  订阅

指针和const限定符

1、指向const对象的指针

const double pi = 3.14;

double *ptr = π        //error:ptr is a plain pointer

const double *cptr = π    //ok:cptr is a pointer to const

不能用void *指针保存const对象的地址,而必须使用const void *类型的指针保存const对象的地址

const int universe = 42;

const void *cpv = &universe;    //ok:cpv is const

void *pv = &universe;        //error:universe is const

允许把非const对象的地址赋给指向const对象的指针

double dval = 3.14;          //dval is a double;its value can be changed

const double *cptr = &dval;      //ok:but can't change dval through cptr

尽管dval不是const对象,但任何企图通过指针cptr修改其值的行为都会导致编译时的错误。

2、const指针

3、指向const对象的const指针

4、指针和typedef

typedef string *pstring;

const pstring cstr;

声明const pstring时,const修饰的是pstring的类型,这是一个指针。因此,该声明语句应该是把cstr定义为指向string类型对象的const指针,这个定义等价于string *const cstr;    //equivalent to const pstring cstr

用typedef写const类型定义时,const限定符加在类型名前面容易引起对所定义的真正类型的误解:

string s;

typedef string *pstring;

const pstring cstr1 = &s;    //written this way the type is obscured

pstring const cstr2 = &s;    //all three decreations are the same type

string *const cstr3 = &s;    //they're all const pointers to string

posted @ 2010-09-28 22:53  BeyondTechnology  阅读(299)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3