Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

C++ -- How to overload operator+=?

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:

  1. How to define the signature of this operator? Specially, what should be used for the return value?

  2. How to implement the function body?

  3. How to use this overload operator?

I have provided a solution as above but I have concerns that it is not correct.

question from:https://stackoverflow.com/questions/4581961/c-how-to-overload-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Returning by reference would be better

Num& operator+=(const Num& rhs){

      this->m_iNumber += rhs.m_iNumber;
      return *this;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...