0

I am learning about overloading operators in c++ and I have done this code aboout the sum of two imaginary numbers, formed by the real part and the imaginary part.

#include<iostream> 
using namespace std; 

class Complex { 
private: 
    int real, imag; 
public: 
    Complex(int r, int i) {
        real = r; 
        imag = i;
    } 


    Complex operator + (Complex const &num1, Complex const &num2) { 
        Complex res; 
        res.real = num1.real + num2.real; 
        res.imag = num1.imag + num2.imag; 
        return res; 
    } 

    void print() { 
        cout << real << " + i" << imag << endl; 
    } 
}; 

int main() 
{ 
    Complex c1(10, 5), c2(2, 4); 
    Complex c3 = c1 + c2;
    c3.print(); 
} 

Something should be wrong because it shows a lot of errors, notes and warnings :(

error: ‘Complex Complex::operator+(const Complex&, const Complex&)’ must take either zero or one argument

error: no match for ‘operator+’ (operand types are ‘Complex’ and ‘Complex’)

note:   ‘Complex’ is not derived from ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’
sonlas10
  • 163
  • 1
  • 10

2 Answers2

5

A binary (2 parameter) operator can't be a class member, it needs to be a standalone function instead:

class Complex {
...
public:
    ...
    friend Complex operator + (Complex const &lhs, Complex const &rhs);
    ...
};

Complex operator + (Complex const &lhs, Complex const &rhs) {
    return Complex(
        lhs.real + rhs.real,
        lhs.imag + rhs.imag
    );
}

Which can also be inlined:

class Complex {
...
public:
    ...
    friend Complex operator + (Complex const &lhs, Complex const &rhs) {
        return Complex(
            lhs.real + rhs.real,
            lhs.imag + rhs.imag
        );
    }
    ...
};

So, a statement like c1 + c2 gets processed as operator+(c1, c2).

A unary (1 parameter) operator, on the other hand, must be a class member that acts on this as the left-side value:

class Complex {
...
public:
    ...
    Complex operator + (Complex const &rhs) const {
        return Complex(
            real + rhs.real,
            imag + rhs.imag
        );
    }
    ...
}; 

Then a statement like c1 + c2 gets processed as c1.operator+(c2).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

The way you have defined operator+ is fine, expect that it needs to be a friend function. Also, note that Complex res; will not compile because you don't have a default constructor.

You could define the function like this:

friend Complex operator + (Complex const &num1, Complex const &num2) { 
   return {num1.real + num2.real, num1.imag + num2.imag};     
}

Here's a demo.

Note also, that I fixed the bug where you are adding the imaginary part of num1 twice.

cigien
  • 57,834
  • 11
  • 73
  • 112