OOP/CPP Complex class to demonstrate operator overloading

/*7. Create a class called COMPLEX that has two private data
called real and imaginary. Include member function
to add two complex objects using operator overloading.
*/
#include <iostream>
 using namespace std;
class complex
{ float real; // real part
float imag;// imaginary part
public:
complex( ) { }// constructor 1
complex(float x, float y)// constructor 2
{real=x; imag=y; }
complex operator+(complex);
void display(void);
};
complex complex::operator+(complex c)
{
complex temp;
temp.real = real + c.real;
temp.imag = imag+ c.imag;
return(temp);
}
void complex::display(void)
{
cout<< real<< “+ j” << imag << “\n”;
}
int main( )
{
complex C1, C2, C3;// invokes constructor 1
C1 = complex(2.5, 3.5);// invokes constructor 2
C2 = complex(1.6, 2.7);
C3 = C1 + C2;
cout << “C1 = “; C1.display( );
cout << “C2 = “; C2.display( );
cout << “C3 = “; C3.display( );
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>