简体   繁体   中英

Overloading operators in C++

See edit at the end

I am trying to overload the + operator in C++ to allow me to add two complex numbers. (add the real and add the imaginary).

Here is my overloaded function:

ComplexNum operator+(ComplexNum x, ComplexNum y){
ComplexNum result;
result.real = (x.getReal() + y.getReal());
result.imag = (x.getImag() + y.getImag());

return result;
}

My Complex number constructor takes in two ints and assigned the first to int real and second to int imag.

When I try add them:

ComplexNum num1 = ComplexNum(1,1);
    ComplexNum num2 = ComplexNum(2,3);
    ComplexNum num3;
    num3 = num1 + num2;
    printf("%d",num3.getReal());

I get 0 as a result. The result should be 3 (the real parts of num1 and num2 added)

EDIT: I figured out what was wrong. I had .getReal() and .getImage() returning double.

Since the arguments of operator+ are declared as values, not references, they will be passed by copy, so if the copy-constructor of ComplexNum doesn't work, that could cause x and y to have a real part of 0.

It's also possible that the addition works, but you lose the real part when you invoke the assignment operator of num3.

Or maybe it's simply the getReal() method that is broken.

It looks to me like either your copy constructor or assignment operator is broken. Could you post the code for those as well?

On a side note: The canonical way to implement operator+ is as a free functions on top of the member operator+= . (The same goes for -= , *= etc., BTW.) For any type T, it should look like this:

T operator+(const T& lhs, const T& rhs)
{
   T tmp(lhs); 
   tmp += rhs; //invoke +=
   return tmp;
}

The rationale for this convention (which, IIRC, Stroustrup attributes to Koenig):

  • + and += (and - and -= etc.) do nearly the same; in order to avoid redundancy, one should be implemented on top of the other
  • += needs to change the left operand, so it should be a member; + leaves its arguments alone, so it should be a free function
  • it's usually easier and/or more efficient to implement non-members on top of members; this case is no exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM