首页 > 其他 > 详细

return *this和return this的区别

时间:2015-03-21 13:56:25      阅读:311      评论:0      收藏:0      [点我收藏+]

?别跟我说, return *this返回当前对象, return this返回当前对象的地址(指向当前对象的指针)。

? ? ? 正确答案为:return *this返回的是当前对象的克隆(当然, 这里仅考虑返回类型为A 没有考虑返回类型为A&?)。return this返回当前对象的地址(指向当前对象的指针), 下面我们来看看程序吧:

[cpp]?view plaincopy技术分享技术分享技术分享

  1. #include?<iostream>??
  2. using?namespace?std;??
  3. ?? ?
  4. class?A??
  5. {??
  6. public:??
  7. ????int?x;??
  8. ????A*?get()??
  9. ????{??
  10. ????????return?this;??
  11. ????}??
  12. };??
  13. ?? ?
  14. int?main()??
  15. {??
  16. ????A?a;??
  17. ????a.x?=?4;??
  18. ?? ?
  19. ????if(&a?==?a.get())??
  20. ????{??
  21. ????????cout?<<?"yes"?<<?endl;??
  22. ????}??
  23. ????else??
  24. ????{??
  25. ????????cout?<<?"no"?<<?endl;??
  26. ????}??
  27. ?? ?
  28. ????return?0;??
  29. }??

? ? ? 结果为:yes

?

? ? ? 再看:

[cpp]?view plaincopy技术分享技术分享技术分享

  1. #include?<iostream>??
  2. using?namespace?std;??
  3. ?? ?
  4. class?A??
  5. {??
  6. public:??
  7. ????int?x;??
  8. ????A?get()??
  9. ????{??
  10. ????????return?*this;?//返回当前对象的拷贝??
  11. ????}??
  12. };??
  13. ?? ?
  14. int?main()??
  15. {??
  16. ????A?a;??
  17. ????a.x?=?4;??
  18. ?? ?
  19. ????if(a.x?==?a.get().x)??
  20. ????{??
  21. ????????cout?<<?a.x?<<?endl;??
  22. ????}??
  23. ????else??
  24. ????{??
  25. ????????cout?<<?"no"?<<?endl;??
  26. ????}??
  27. ?? ?
  28. ????if(&a?==?&a.get())??
  29. ????{??
  30. ????????cout?<<?"yes"?<<?endl;??
  31. ????}??
  32. ????else??
  33. ????{??
  34. ????????cout?<<?"no"?<<?endl;??
  35. ????}??
  36. ?? ?
  37. ????return?0;??
  38. }??

? ? ?结果为:

4

no

return *this和return this的区别

原文:http://www.cnblogs.com/hdk1993/p/4355472.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!