Search code examples
c++operator-overloadingnon-member-functions

operator overloading and non-member functions c++


I have written a class for complex numbers in which I have overloaded the operator + and everything works fine, however I need to implement this as a non-member function and I am not sure how, or why there is a benefit of doing so.

Here is my code .h:

class Complex
{
private:
    double a;
    double b;

public:
    Complex();
    Complex(double aGiven);
    Complex(double aGiven, double bGiven);

    double aGetValue();
    double bGetValue();    
    double operator[](bool getB);

    Complex add(Complex &secondRational);
    Complex operator+(Complex &secondRational);
}

.cpp:

Complex Complex::add(Complex &secondRational)
{
    double c = secondRational.aGetValue();
    double d = secondRational.bGetValue();
    double anew = a+c;
    double bnew = b+d;
    return Complex(anew,bnew);
}

Complex Complex::operator+(Complex &secondRational)
{
    return add(secondRational);
}

Any help on how to make these as non-member functions will be greatly appreciated!


Solution

  • Here is the addition operator outside of the class:

    Complex operator+(const Complex& lhs, const Complex& rhs) {
      //implement the math to add the two
      return Complex(lhs.aGetValue() + rhs.aGetValue(),
                     lhs.bGetValue() + rhs.bGetValue());
    }
    

    Of course you will need to declare aGetValue() and bGetValue() as const:

    double aGetValue() const {return a;}
    double bGetValue() const {return b;}