what is return type of assignment operator?

前端 未结 3 595
离开以前
离开以前 2020-11-29 02:44

I am just starting C++. I am a bit confused about the return type of assignment and dereference operator. I am following the book C++ Primer. At various occasions, the autho

3条回答
  •  时光说笑
    2020-11-29 03:18

    They can both be anything, but usually operator = returns the current object by reference, i.e.

    A& A::operator = ( ... )
    {
       return *this;
    }
    

    And yes, "reference to the type of left hand operand" and "lvalue referring to left hand operand" mean the same thing.

    The dereference operator can have basically any return type. It mostly depends on the logic of the program, because you're overloading the operator that applies to an object, not to a pointer to the object. Usually, this is used for smart pointers, or iterators, and return the object they wrap around:

    struct smart_ptr
    {
       T* innerPtr;
       T* smart_ptr::operator* ()
       {
          return innerPtr;
       }
    }
    
    smart_ptr p; 
    T* x = *p;  
    

提交回复
热议问题