| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 563 人关注过本帖
标题:字符串常量 问题
只看楼主 加入收藏
duffebear
Rank: 1
等 级:新手上路
威 望:2
帖 子:172
专家分:0
注 册:2007-1-30
收藏
 问题点数:0 回复次数:3 
字符串常量 问题

上C++选修课,老师指出了一个我以前没怎么注意的问题,形如
"char * pStr="Abcd";"的语句中的pStr指向的是字符串常量,所以程序中对pStr指向的区域只能读,
不能写(如 pStr[1]='c' ;这样的操作),否则即算编译成功,也会运行失败,而且程序测试也似乎如此。

而我在《 effective c++》上

条款21: 尽可能使用const
里面有下面一句
...
char *p = "hello"; // 非const指针, 非const数据

这里是不是有问题

搜索更多相关主题的帖子: 常量 字符 
2007-11-02 13:09
yuyunliuhen
Rank: 6Rank: 6
等 级:贵宾
威 望:20
帖 子:1435
专家分:0
注 册:2005-12-12
收藏
得分:0 

实践证明一切吧.如果测试都是这样的话。去这里看是否有修正:
Scott Meyers---Modification History and Errata List for Effective C++
http://www.aristeia.com/BookErrata/ec++2e-errata_frames.html


Go confidently in the  directions of your dreams,live the life you have imagined!Just do it!
It is no use learning without thinking!
2007-11-02 13:51
duffebear
Rank: 1
等 级:新手上路
威 望:2
帖 子:172
专家分:0
注 册:2007-1-30
收藏
得分:0 

上面看的是第一版(因为是中文,方便些)
刚刚看了下 effective C++ 第三版(英文版),看来第一版的条款21: 尽可能使用const 那里的确有错误

第三版
Item 3: Use const whenever possible

在这里与一版不同,修改为了:

char greeting[] = "Hello";

char *p = greeting; // non-const pointer,

// non-const data

const char *p = greeting; // non-const pointer,

// const data

char * const p = greeting; // const pointer,

// non-const data

const char * const p = greeting; // const pointer,

// const data



看书还得看最新版 ,尽管是 英文


死后定当长眠 生前何须久睡
2007-11-02 15:44
yuyunliuhen
Rank: 6Rank: 6
等 级:贵宾
威 望:20
帖 子:1435
专家分:0
注 册:2005-12-12
收藏
得分:0 

书还是看原版好!


Go confidently in the  directions of your dreams,live the life you have imagined!Just do it!
It is no use learning without thinking!
2007-11-02 16:23
快速回复:字符串常量 问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.013604 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved