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; }
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.