Operator Overloading?
Mar 31, 2014 at 11:05am UTC
Hello!
I'm trying to overload the + operator to have it add together two complex numbers.
This is my code thus far:
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include "Complex.h"
using namespace std;
int main(){
Complex a(1,1.3);
Complex b(2,3);
Complex c = a + b;
cout<< c.real << " + j" << c.imag << endl;
}
Complex.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex{
public :
double real, imag;
Complex();
Complex(double , double );
Complex operator +(const Complex&);
};
#endif
Complex.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include "Complex.h"
using namespace std;
Complex::Complex(){
}
Complex::Complex(double r, double i){
real = r;
imag = i;
}
Complex Complex::operator +(const Complex& other){
Complex resultImag;
Complex resultReal;
resultReal.real = real + other.real;
resultImag.imag = imag + other.imag;
return (resultReal, resultImag);
}
I'm not getting any errors whilst compiling, but my output is
4.24399e-314 + j4.3 when it should be
3 + j4.3 .
It's just the real component that I can't get right.
Any help would be much appreciated.
Last edited on Mar 31, 2014 at 11:05am UTC
Mar 31, 2014 at 11:09am UTC
This is because you have done something with the comma operator, which only returns the second statement. You may want to change your operator function to something like this (note the one complex number for return values):
1 2 3 4 5 6
Complex Complex::operator + (const Complex& other) {
Complex result;
result.real = this ->real + other.real;
result.imag = this ->imag + other.imag;
return result;
}
Or alternately, as a small function:
1 2 3
Complex Complex::operator + (const Complex& other) {
return Complex(this ->real + other.real, this ->imag + other.imag);
}
Mar 31, 2014 at 11:18am UTC
Oh, I see!
Thank you!
Topic archived. No new replies allowed.