| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1206 人关注过本帖
标题:[讨论]反思大家之前讨论过的一个问题
取消只看楼主 加入收藏
百年不亮
Rank: 3Rank: 3
等 级:新手上路
威 望:8
帖 子:789
专家分:0
注 册:2006-4-14
结帖率:100%
收藏
 问题点数:0 回复次数:1 
[讨论]反思大家之前讨论过的一个问题
之前的一个帖子中提到关于自增前缀和后缀的问题,帖子在这里:http://bbs.bc-cn.net/dispbbs.asp?boardid=56&replyid=58792&id=124908&page=20&skin=0&star=1
int main()
{
int x=5;
int *p=&++x;
int *q=&x++; //error C2102: '&' requires l-value
return 0;
}

Cpp1.cpp
C:\Documents and Settings\Administrator\桌面\daima\Cpp1.cpp(6) : error C2102: '&' requires l-value


最后大家争论的焦点就在为什么&++x合法,而&x++会出错,有人提到我们在c++中重载前缀自增时直接将原始对象加一,最后返回原始对象的引用,所以&++x取的是原始对象的地址,是合法的。而在后缀的实现中是通过将原始对象的值赋给一个临时对象,再将原始对象加一,最后返回临时对象的值,&x++就是取一个临时对象的地址,所以是错误的操作。我看后觉得这是有道理的,但是这只是推测,不敢确定c/c++中内置类型也是这样实现的,近来翻看Bjarne Stroustrup 的 <<The C++ Programming Language>>,发现有一段话如下:

6.2.5 Increment and Decrement
The ++ operator is used to express incrementing directly,rather than expressing it indirectly using a combination of an addition and an assignment. By definition, ++lvaue means lvalue+=1, which again means lvalue=lvalue+1 provided lvalue has no side effects. The expression denoting the object to be incremented is evalued once(ovly). Decrementint is similarly expressed by the -- operator. The operators ++ and -- can be used as both prefix and postfix operators.The value of ++x is the new(that is, incremented)value of x. For example, y=++x is equivalent to y=(x+=1). The value of x++, however, is the old value of x. For example, y=x++ is equivalent to y=(t=x,x+=1,t), where t is a variable of the same type as x.

最后两句话就是我关心的:x++的值是x自增之前的旧值。例如y=x++相当于y=(t=x,x+=1,t),其中t是和x相同类型的变量

对比y=++x is equivalent to y=(x+=1) 和 y=x++ is equivalent to y=(t=x,x+=1,t),可以看出前缀和后缀的本质差别,&++x等价于&(x+=1)即(x+=1,&x); &x++等价于&(t=x,x+=1,t)即&t.

有了Bjarne Stroustrup他老人家的话自己终于放心了。
搜索更多相关主题的帖子: int skin 
2007-05-19 19:57
百年不亮
Rank: 3Rank: 3
等 级:新手上路
威 望:8
帖 子:789
专家分:0
注 册:2006-4-14
收藏
得分:0 

回5楼的:
我不是说了吗,在自定义类型中,就是我们自己的类中,是这样的,这个是可以肯定的,但是,注意我说的是但是c/c++的内置类型是怎样的,我不知道,在没有一个权威确认的情况下,即使这样是解释的通,我们也只能说推测,不是吗?我在看了Bjarne Stroustrup的书之后才可以确认。
我认为讨论技术问题应该严谨,不能因为自己定义的类中重载++是那样实现的就说内置的类型如int类型也是这样。或许你会说我死板。

2007-05-21 19:44
快速回复:[讨论]反思大家之前讨论过的一个问题
数据加载中...
 
   



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

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