重载后缀++不明白的地方

zwlzwlzwl 2008-10-11 03:25:44
返回const:
const Byte Byte::operator++(int)----------------//第一种写法
{
Byte Before(*this);
++(*this)
return Before;
}
返回非const:
Byte Byte::operator++(int)-------------------//第二种写法
{
Byte Before(*this);
++(*this)
return Before;
}

在c++编程思想的P279页中对后缀重载返回值有说明,operator++(int)返回临时对象,临时对象自动为常量
调用方式:
Byte a;
(a++).func() ///func为非const成员
对于第一种写法编译器肯定会报错,但对于第二种写法编译器并没报错,按照c++编程思想的说法,编译器会阻止,是编译器的原因吗?
我知道第二种写法会导致a++++的问题,违背了++++的语义,不建议使用,所以返回const。

...全文
139 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
thecrypig 2008-10-11
  • 打赏
  • 举报
回复
嗯,我得学好英文,得考四级.....

楼主帮顶
帅得不敢出门 2008-10-11
  • 打赏
  • 举报
回复
看看此贴 说的好热烈 可能对你有帮助
http://topic.csdn.net/t/20031209/21/2546246.html

matrixdwy 2008-10-11
  • 打赏
  • 举报
回复
LZ请看第八章:Constants--Returning by const value--Temporaries一节,英文版是第348页

However, notice the expressions that are legal:
f5() = X(1);
f5().modify();
Although these pass muster for the compiler, they are actually
problematic.
f5( ) returns an X object, and for the compiler to satisfy
the above expressions it must create a temporary to hold that
return value. So in both expressions the temporary object is being
modified, and as soon as the expression is over the temporary is
cleaned up. As a result, the modifications are lost so this code is
probably a bug – but the compiler doesn’t tell you anything about
it. Expressions like these are simple enough for you to detect the
problem, but when things get more complex it’s possible for a bug
to slip through these cracks.


也就是说这种错误编译器是不会报警的。这种错误是比较明显的,所以你应该自己去
发现解决。
boys2002 2008-10-11
  • 打赏
  • 举报
回复
还真没接触过 这个~~~

顶一下 占个SOFA


别忘记给点分啊 楼上 ~~~

65,211

社区成员

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

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