c++ - typedef的理解问题?
怪我咯
怪我咯 2017-04-17 11:43:56
[C++讨论组]
typedef char *pstring;
const pstring cstr = 0;         //char *const cstr
const pstring *ps;              //char *const *ps

注释里的代码是否等价于注释前的代码?
1. 即const pstring cstr = 0;等价于char *const cstr = 0;

2.如果是的话,那这样写pstring const cstr = 0;岂不是更容易理解吗?

3.const pstring cstr = 0;pstring const cstr = 0;是一样的意思,我说的对吗?

求助,先行谢过!

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
PHP中文网
  1. 是的。

  2. 是的,我觉得书上如此举例,是为了故意制造混淆看你能否火眼金睛。

  3. 对。


说一下里面涉及的概念。

typedef char *pstring;
const pstring cstr = 0;         //char *const cstr

cstr is a constant pointer to char. (注意,const 修饰的是 pointer.)

const char * vs char * const ?

  • const char * is a pointer to a const char.

  • char * const is a constant pointer to char.

  • char * const <==> const pstring

  • const char * <==> char const *

所以 @snailcoder 对于 const 在 * 左侧还是右侧的理解是正确的。但对于 typedef声明的理解稍有偏差。

容我直接引用书上的解释,说的很清楚了:

The base type in these declarations is const pstring. As usual, a const that appears in the base type modifies the given type. The type of pstring is “pointer to char.” So, const pstring is a constant pointer to char—not a pointer to const char.

恰好,这也解释了你第三个疑虑,const 出现在 base type 旁边,就修饰的是 base type,在左边在右边没半点差别。(这里的 base type 是 char *, 是个指针。)

以上。

阿神
const pstring cstr = 0;//等价于const char *cstr = 0;
const pstring *ps;//等价于const char **ps;

但是,const char *cstr不等价于char* const cstrconst char **ps不等价于char* const *ps
用const修饰字符指针的规则很简单:如果const位于左侧(例如const char *cstr),则指针指向的内容是个常量;如果const位于右侧(例如char* const cstr),则指针本身是个常量。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号