有何不同?

zf0579 2003-04-29 04:39:18
为何以下两个操作符重载
第一个为Point& Point::operator++()
第二个为Point Point::operator++(int)
为什么第一个Point后面跟& 而第二个Point后面没有呢?

// Define prefix increment operator.
Point& Point::operator++()
{
_x++;
_y++;
return *this;
}

// Define postfix increment operator.
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}
...全文
42 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
WhatCanIdoing 2003-05-01
  • 打赏
  • 举报
回复
never return a reference to a local object or to a dereferenceed pointer initialized by new within the function

千万不要传回“函数内 local 对象的 refernce ” 或“函数内的以 new 获得的指针所指的对象的 reference ”

《effective c++》

// Define postfix increment operator.
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp; 函数内 local 对象
}
genewujing 2003-04-29
  • 打赏
  • 举报
回复
我比较赞同atto的观点!
zf0579 2003-04-29
  • 打赏
  • 举报
回复
基本同意ChenAxue的观点
zf0579 2003-04-29
  • 打赏
  • 举报
回复
我觉得atto与yeyuboy的回答都不太正确。我想是因为第一个返回引用指向自己 也就是*this,this指向调用该前缀++的对象。而第二个如果采用&,则应该返回temp,但是temp是局部变量,函数返回后就毫无意义,所以不能用&,只能采用值传递,拷贝份变量。
这是我的理解。
chenAxue 2003-04-29
  • 打赏
  • 举报
回复
第一个因为没有使用局部变量,而是返回this指针,为了接收指针的内容,所以要定义引用;第二个因为使用了局部变量,所以接收该变量不必使用引用
yeyuboy 2003-04-29
  • 打赏
  • 举报
回复
可能是算法的原因,对于前缀方式,必须返回引用,它会先对要自增的对象进行自增然后返回其引用。而对于后缀方式是返回其值,然后再自增,若返回引用,就无法对其自增。
------------------------------->这是个人认识,但若由我进行设计也只能这样设计!
atto 2003-04-29
  • 打赏
  • 举报
回复
第一个是++i,先加加再返回,所以可以返回Point&
第二个是i++,先返回再加加,所以只能返回Point, 变量本身还要++呢!
zf0579 2003-04-29
  • 打赏
  • 举报
回复
我想第一个返回引用 第二个返回值 但是为何要如此呢?

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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