C ++ - 如何重载operator + =? [英] C++ -- How to overload operator+=?
本文介绍了C ++ - 如何重载operator + =?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下代码段
: class Num
{
public:
Num(int iNumber = 0):m_iNumber(iNumber){}
Num operator + =(const Num& rhs)
{
this-> m_iNumber =(this-> ; m_iNumber + rhs.m_iNumber);
return * this;
}
private:
int m_iNumber;
};
// ======================================== ===================
int _tmain(int argc,_TCHAR * argv [])
{
Num a(10);
Num b(100);
b + = a;
return 0;
}
我想知道如何正确重载
- p>如何定义此运算符的签名?
-
如何实现函数体?
-
如何使用此重载运算符?
我提供了一个如上所述的解决方案,
解决方案
由参考返回会更好
Num& operator + =(const Num& rhs){
this-> m_iNumber + = rhs.m_iNumber;
return * this;
}
Given the following code snippet,
class Num
{
public:
Num(int iNumber = 0) : m_iNumber(iNumber) {}
Num operator+=(const Num& rhs)
{
this->m_iNumber = (this->m_iNumber + rhs.m_iNumber);
return *this;
}
private:
int m_iNumber;
};
//===========================================================
int _tmain(int argc, _TCHAR* argv[])
{
Num a(10);
Num b(100);
b += a;
return 0;
}
I would like to know how to correctly overload the operator+=
.
Questions:
How to define the signature of this operator? Specially, what should be used for the return value?
How to implement the function body?
How to use this overload operator?
I have provided a solution as above but I have concerns that it is not correct.
解决方案
Returning by reference would be better
Num& operator+=(const Num& rhs){
this->m_iNumber += rhs.m_iNumber;
return *this;
}
这篇关于C ++ - 如何重载operator + =?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文