Experiment 3
Aim
To implement a Complex Number class with necessary
operator overloading and type conversions, including integer-to-complex,
double-to-complex and complex-to-double conversions.
Objectives
- To
understand operator overloading.
- To
implement arithmetic operations on complex objects.
- To
understand conversion constructors.
- To
implement user-defined conversion from Complex to double.
Theory
Operator overloading allows operators such as +, -, * and /
to work with user-defined objects.
A conversion constructor can convert a value of
another type into a class object. A conversion operator allows
conversion of a class object into another data type.
Algorithm
- Define
a Complex class with real and imaginary parts.
- Create
a constructor accepting real and imaginary values.
- Implement
overloaded +, -, * and / operators.
- Allow
integer and double values to be converted into Complex objects.
- Define
a conversion operator to convert Complex into double.
- Display
the results.
Program
#include <iostream>
using namespace std;
class Complex {
double real, imag;
public:
Complex(double r =
0, double i = 0) {
real = r;
imag = i;
}
Complex
operator+(Complex c) {
return
Complex(real + c.real, imag + c.imag);
}
Complex
operator-(Complex c) {
return
Complex(real - c.real, imag - c.imag);
}
Complex
operator*(Complex c) {
return
Complex(real * c.real - imag * c.imag,
real * c.imag + imag * c.real);
}
Complex
operator/(Complex c) {
double d =
c.real * c.real + c.imag * c.imag;
return
Complex(
(real *
c.real + imag * c.imag) / d,
(imag *
c.real - real * c.imag) / d
);
}
operator double()
{
return real;
}
void display() {
cout <<
real << " + " << imag << "i\n";
}
};
int main() {
Complex a(3, 4),
b(2, 1), c;
c = a + b;
cout <<
"Addition: ";
c.display();
c = a - b;
cout <<
"Subtraction: ";
c.display();
c = a * b;
cout <<
"Multiplication: ";
c.display();
c = a / b;
cout <<
"Division: ";
c.display();
Complex x = 5;
cout <<
"Integer to Complex: ";
x.display();
Complex y = 5.5;
cout <<
"Double to Complex: ";
y.display();
double d = a;
cout <<
"Complex to double: " << d << endl;
return 0;
}
Result
Thus, the Complex Number class was successfully implemented
with operator overloading and type conversions.
Viva Questions
- What
is operator overloading?
- Which
operators can be overloaded?
- What
is a conversion constructor?
- What
is a conversion operator?
- How
is integer converted into Complex?
- What
is the purpose of operator double()?
No comments:
Post a Comment