在谈const?

Crazy_hand 2008-11-01 12:15:14
使用const的大方向:就是为了 让它修饰的那个变量的值不会被更改:
但确出现了两种写法不同,作用相同的形式:
1 指向const对象的指针:
(i) 指向const对象的指针的值是不许被更改的
(ii) 可以把一个const对象的地址贼值给一个指向const对象的指针:
(iii) 也可以把一个普通的对象的地址贼值给一个指向const对象的指针:
任何想通过这个指针来修改这个普通对象的值都会error;
但你可以使用这个普通的对象本身修改值。
2 const指针:
(i) const指针本身是不可以修改的(这个指针只可以指向它的初始对象)
(ii) 但const指针指向的对象的值是可以修改的( 可以用它来修改它所指向的对象的值)
-------
不知我上面的理解对不对?
--还有个问题就是关于typedef的
书上说

typedef string *ptr;
const ptr name;

这样的声明会扩展成 string *const name;

为什么?

如果const ptr name会被扩展成 string *const name;
那么如果我想得到 const string* name 这个形式应该怎样typedef ?
...全文
88 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
hityct1 2008-11-01
  • 打赏
  • 举报
回复
const修饰指针时,可简单的理解为限制作用。

int a=1,b=2;
const int* p1=&a;//限制所指向的值的更改
int* const p2=&b;//限制指向的更改



至于想得到const string* name 这个形式,我认为只能这样:
typedef string ptr;
const ptr* name;
jackzhhuang 2008-11-01
  • 打赏
  • 举报
回复
这个我还真没想过,我看只能这样吧:

typedef const char * LPCSTR

LPCSTR lpstr = "hello world";
太乙 2008-11-01
  • 打赏
  • 举报
回复
因为你的const是修饰ptr的!
nianhuaxpj 2008-11-01
  • 打赏
  • 举报
回复
c++ templates一书中也提到了这个问题,楼上正解。
Vegertar 2008-11-01
  • 打赏
  • 举报
回复

typedef 取的是意义上的同名, 而不是文本替换.
下面是从C++ Primer 4th上摘录的:
指针和 typedef
The use of pointers in typedefs (Section 2.6, p. 61) often leads to surprising results. Here is a question almost everyone answers incorrectly at least once. Given the following,

在 typedef(第 2.6 节)中使用指针往往会带来意外的结果。下面是一个几乎所有人刚开始时都会答错的问题。假设给出以下语句:

typedef string *pstring;
const pstring cstr;

what is the type of cstr? The simple answer is that it is a pointer to const pstring. The deeper question is: what underlying type does a pointer to const pstring represent? Many think that the actual type is

请问 cstr 变量是什么类型?简单的回答是 const pstring 类型的指针。进一步问:const pstring 指针所表示的真实类型是什么?很多人都认为真正的类型是:

const string *cstr; // wrong interpretation of const pstring cstr

That is, that a const pstring would be a pointer to a constant string. But that is incorrect.

也就是说,const pstring 是一种指针,指向 string 类型的 const 对象,但这是错误的。

The mistake is in thinking of a typedef as a textual expansion. When we declare a const pstring, the const modifies the type of pstring, which is a pointer. Therefore, this definition declares cstr to be a const pointer to string. The definition is equivalent to

错误的原因在于将 typedef 当做文本扩展了。声明 const pstring 时,const 修饰的是 pstring 的类型,这是一个指针。因此,该声明语句应该是把 cstr 定义为指向 string 类型对象的 const 指针,这个定义等价于:

// cstr is a const pointer to string
string *const cstr; // equivalent to const pstring cstr

太乙 2008-11-01
  • 打赏
  • 举报
回复
至于怎么定义?这个问题,为啥不能简单化呢?
typedef const string* ptr;
帅得不敢出门 2008-11-01
  • 打赏
  • 举报
回复

typedef string *ptr;
const ptr name;

这样的声明会扩展成 string *const name;

因为这个const 给予整个指针以常量性
http://topic.csdn.net/t/20040904/22/3340926.html

64,688

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧