gpt4 book ai didi

c++ - 用作左值的成员函数

转载 作者:行者123 更新时间:2023-11-30 01:22:11 25 4
gpt4 key购买 nike

我正在实现一个 Complex 类作为练习,我正在查看这个 file作为指南。
在此文件中的某个位置,我发现了一个奇怪的重载运算符:

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

如何将 __r.real() 用作 lvalue?我试图在我的类中实现它,以及 real() 的两个重载定义,但当然它会返回一些错误。
有人可以告诉我我缺少什么吗?

这些是函数 real()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; }

最佳答案

它的 real() 返回对 _M_real; 成员的引用。引用可以用作左值。

为了让您的也能做到这一点,您还需要返回一个引用。

关于c++ - 用作左值的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16841332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com