[Solved] Addition operator overloading for complex numbers [duplicate]


There are tons of errors here, from incorrect attempts to overload operators to using data members by the wrong name. I’ll step through what I see.


When defining the binary operator+ as a member function it only takes one argument, which is the right-hand argument to + (the left-hand is implicitly *this).

Also your operators use the nonexistent fields r and i — you probably meant real and imaginary.

class Complex
{
    // ...

public:
    // Wrong, will cause compile-time errors:
    // Complex operator+(Complex c1, Complex c2);  

    // Right:
    Complex operator+(Complex c);
};

Complex Complex::operator+(Complex c) 
{
    Complex result;
    result.real = real + c.real;
    result.imaginary = imaginary + c.imaginary;
    return result;
}

Alternatively you can define the operator as a free function instead of as a member of the class, but you’d have to make it a friend of the class since it accesses private members:

class Complex
{
    // ...

    friend Complex operator+(Complex, Complex);
};

Complex operator+(Complex c1, Complex c2) 
{
    Complex result;
    result.real = c1.real + c2.real;
    result.imaginary = c1.imaginary + c2.imaginary;
    return result;
}

Similarly, your operator<< overload for std::ostream should be a free function, and needs to be fixed to use real and imaginary. However, since these members are private to Complex, this will fail unless you make this operator a friend of Complex. Since ostream is an abstract type you can’t accept or return instances by value, you need to use references. Further you don’t actually return anything.

class Complex
{
    // ...

    friend ostream & operator<<(ostream &, Complex);
};

ostream & operator<<(ostream & out, Complex number)
{
    out << number.real << "+" << number.imaginary << endl;
    return out;
}

Your Complex class is missing a default constructor, so you can’t declare variables like Complex c; because this requires the existence of the default constructor:

class Complex
{
    // ...

public:
    Complex();
};

Complex::Complex() : real(0), imaginary(0) { }

11

solved Addition operator overloading for complex numbers [duplicate]