【问题标题】:return object of operator= overloading in c++在c ++中返回运算符=重载的对象
【发布时间】:2020-08-26 02:37:14
【问题描述】:

在 C++ 中实现 operator= 时返回 *this 或给定参数有什么区别?使用其中之一更好或更有用吗?如果是,为什么?

   class Object {
   public:
      Object operator=(Object Obj) {
         return *this;
      }
   }

对比

   class Object {
   public:
      Object operator=(Object Obj) {
         return Obj;
      }
   }

【问题讨论】:

  • 您应该返回对当前对象的引用,而不是一个全新的对象。
  • 这能回答你的问题吗? What is The Rule of Three?

标签: c++ operator-overloading this operator-keyword


【解决方案1】:

X& operator=( X const& ) { return *this; } 匹配int= 的语义。你给出的其他建议没有。当有疑问时匹配int的语义。

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2014-03-14
    • 2012-04-23
    • 2011-07-23
    相关资源
    最近更新 更多