Q#1). Define a class to represent a complex number called Complex. Provide the following member
functions:-
1. To assign initial values to the Complex object.
2. To display a complex number in a+ib format.
3. To add 2 complex numbers. (the return value should be complex)
4. To subtract 2 complex numbers
Write a main function to test the class.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Complex{
private:
  double x;
  double y;
public:
  Complex() {Â
    x = 0;Â
    y = 0;Â
    Â
  }
  Complex(double a, double b) {Â
    x = a;Â
    y = b;Â
  }
  Complex operator + (Complex const& c1) {
    Complex result;
    result.x = x + c1.x;
    Â
    result.y = y + c1.y;
    Â
    return result;
  }
  Complex operator - (Complex const& c) {
  Â
  Complex result;
  result.x = x - c.x;
  Â
  result.y = y - c.y;
  Â
  return result;
  Â
  }
string display()
{
string result = "";
ostringstream a_sstream;
a_sstream << x;
string a_str = a_sstream.str();
ostringstream b_sstream;
b_sstream << y;
string b_str = b_sstream.str();
if (y < 0)
result = a_str + b_str + "i";
else
result = a_str + "+" + b_str + "i";
return result;
}
};
int main()
{
Complex c1(2.5, 4.1);
Complex c2(-3.4, -2.8);
Complex c3 = c1 + c2;
cout <<"Addition: "<< c3.display()<<endl;
Complex c4 = c1 - c2;
cout <<"Substraction: "<<c4.display()<<endl;
return 0;
}
Comments
Leave a comment