0

My point in a code is that I want to overload the + operator, so I could add two class instances. For example, consider a class that has 2 double members, Real and Complex. Class is called Complex and I have created 2 instances, c1 and c2. Then I want to create a c3 instance which is the addition of values of c1 and c2. I have a copy constructor and + operator overloader. (Copy, so I can assign the new instance made by the + overloader to c3): Here is my class:

class Complex {
    double real;
    double imaginary;
public:
    Complex();
    Complex(double real, double imaginary);
    ~Complex();
    Complex(const Complex &other);
    Complex operator+(const Complex &other, const Complex &other2);
};

And the CPP file:

Complex Complex::operator+(const Complex &other1, const Complex &other2){
    return(Complex(other1.real+other2.real, other1.imaginary+other2.imaginary));
}

Complex::Complex(){};

Complex::Complex(double real, double imaginary): real(real), imaginary(imaginary){};

Complex::~Complex(){};

Complex::Complex(const Complex &other){
    this->real = other.real;
    this->imaginary = other.imaginary;
}

I know that I can create a friend operator but I want to keep everything in a class. No reason for that, just I like it that way.

  • When implementing `operator+` as a member function, it must only take one argument. The first operand is `this`, the second operand is the passed argument. So modify the function to only take one argument (`other`), and implement the body of the function like this: `return(Complex(real + other.real, imaginary + other.imaginary));` – Nikos C. Dec 09 '17 at 12:41
  • Also, you should know that you're reinventing the wheel. C++ already has a type for complex numbers. See: http://en.cppreference.com/w/cpp/numeric/complex – Nikos C. Dec 09 '17 at 12:44

0 Answers0