zoukankan      html  css  js  c++  java
  • 指针和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

  • 相关阅读:
    读写文件
    c++ 中的 -> :: : .
    CDH安装步骤
    MySQL安全配置向导mysql_secure_installation详解
    Linux下彻底卸载mysql详解
    安装mysql警告: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
    为Hadoop集群选择合适的硬件配置
    利用cm压缩包手动安装cm和cdh
    CM5.11与CDH5.11安装使用说明
    法的本体
  • 原文地址:https://www.cnblogs.com/BeyondTechnology/p/1837929.html
Copyright © 2011-2022 走看看