hey guys
I wrote a simple Complex Class and overload input/output and +/- Operators in it!But there is something that doesn't work correctly!I can print an object of that class but I can't print sum of two object or something like that!
Here is My Code:
Code:
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
using namespace std;
class Complex
{
friend ostream & operator<<(ostream &, const Complex &);
friend istream & operator>>(istream &, Complex &);
public:
Complex(double = 1, double = 1);
Complex & operator+(const Complex &);
Complex & operator-(const Complex &);
//const Complex & operator=(const Complex &);
private:
double real, imag;
};
#endif // COMPLEX_H
Code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include "Complex.h"
using namespace std;
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
Complex & Complex::operator+(const Complex &c)
{
Complex result(this->real + c.real, this->imag + c.imag);
return result;
}
Complex & Complex::operator-(const Complex &c)
{
Complex result(this->real - c.real, this->imag - c.imag);
return result;
}
ostream & operator<<(ostream &output, const Complex &c)
{
output << "(" << c.real << ", " << c.imag << ")";
return output;
}
istream & operator>>(istream &input, Complex &c)
{
string strtmp;
input >> strtmp;
for(int i = 0;i < strtmp.length();i++)
{
if(strtmp[i] == '(' || strtmp[i] == ')' || strtmp[i] == ',')
strtmp[i] = ' ';
}
c.real = stod(strtmp);
input >> strtmp;
for(int i = 0;i < strtmp.length();i++)
{
if(strtmp[i] == '(' || strtmp[i] == ')' || strtmp[i] == ',')
strtmp[i] = ' ';
}
c.imag = stod(strtmp);
return input;
}
Code:
// Complex.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "Complex.h"
using namespace std;
int main()
{
Complex c1(2, 2), c2(3, 3), c3, c4;
c3 = c1 + c2;
cout << c3;
cout << (c1 + c2);
return 0;
}
cout << c3 is Working fine But cout << c1 + c2 is not giving me correct output!