Question

I'm implementing a Complex class as exercise, and I'm looking at this file as guideline.
At some point in this file I found a strange overloaded operator:

template<typename _Tp>
    inline complex<_Tp>
    operator+(const complex<_Tp>& __x, const _Tp& __y)
    {
        complex<_Tp> __r = __x;
        __r.real() += __y;
        return __r;
    }

How It's possible to use __r.real() as lvalue? I tried to implement it in my class, along with the two overloaded definitions of real(), but of course it gives me back a number of errors.
Could someone tell me what I'm missing?

Those are the definitions of the functions real() and imag():

template<typename _Tp>
    inline _Tp&
    complex<_Tp>::real() { return _M_real; }

template<typename _Tp>
    inline const _Tp&
    complex<_Tp>::real() const { return _M_real; }

template<typename _Tp>
    inline _Tp&
    complex<_Tp>::imag() { return _M_imag; }

template<typename _Tp>
    inline const _Tp&
    complex<_Tp>::imag() const { return _M_imag; }
Était-ce utile?

La solution 2

The definition you show for non-const real return an a reference _Tp& which can be used as an l-value just fine. I am guessing your version does not return a reference and therefore will not work.

This article Understanding lvalues and rvalues in C and C++ is a great reference on this topic.

Autres conseils

Its real() is returning a reference to the _M_real; member. The reference can be used as an lvalue.

To make yours able to do the same, you'll need to return a reference as well.

Notice that the implementations return a _Tp&; that is, a reference to _Tp. This makes the return value an l-value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top