问题描述
我有以下代码,基本上是重载+和+ =代表
复数。它工作正常,但有人可以告诉我如何在+ =的定义中使用
重载+而不是从头开始编写函数
?
谢谢,
Ciao。
// ----------------- ------------------------------------------------
inline Complex Complex :: operator +(const Complex& right)const
{
复杂myComplex(real()+ right.real() ,imag()+ right.imag());
return(myComplex);
}
// ------ -------------------------------------------------- ---------
inline const Complex& Complex :: operator + =(const Complex& right)
{
m_dRe + = right.real();
m_dIm + = right.imag();
返回(* this);
}
// ----------- -------------------------------------------------- -----
Hi,
I have the following code, which is basically overloading + and += for
complex numbers. It works fine, but can someone tell me how to use the
overloaded + in the definition of += rather than write the function
from scratch?
Thanks,
Ciao.
//-----------------------------------------------------------------
inline Complex Complex::operator + (const Complex &right) const
{
Complex myComplex( real() + right.real(), imag() + right.imag());
return ( myComplex );
}
//-----------------------------------------------------------------
inline const Complex & Complex::operator += (const Complex &right)
{
m_dRe += right.real();
m_dIm += right.imag();
return ( *this );
}
//------------------------------------------------------------------
推荐答案
好吧,你可以编写operator + = as
Compex& Complex :: operator + =(const Complex& right){
* this = * this + right;
}
你不是通常期望+ =返回一个const引用。
Well, you could write operator += as
Compex& Complex::operator+=(const Complex& right) {
*this = *this + right;
}
You don''t normally expect += to return a const reference.
出于效率原因,你通常想要反过来这样做。
试试这个:
inline Complex Complex :: operator +(Complex right) )const
{
right + = * this;
返回权利;
}
inline Complex& Complex :: operator + =(const Complex& right)
{
m_dRe + = right.real();
m_dIm + = right.imag();
返回* this;
}
- -
见到你。
You normally want to do it the other way around, for efficiency reasons.
Try this:
inline Complex Complex::operator+(Complex right) const
{
right += *this;
return right;
}
inline Complex &Complex::operator+=(const Complex &right)
{
m_dRe += right.real();
m_dIm += right.imag();
return *this;
}
--
Be seeing you.
这篇关于重载+ =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!