๐Operator overloading
#include <iostream>
class Complex {
private:
double real;
double imag;
public:
// Constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// Overload the + operator
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// Overload the * operator
Complex operator*(const Complex& other) const {
return Complex(real * other.real - imag * other.imag,
real * other.imag + imag * other.real);
}
// Overload the == operator
bool operator==(const Complex& other) const {
return (real == other.real) && (imag == other.imag);
}
// Overload the << operator for easy output
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real;
if (c.imag >= 0) os << "+";
os << c.imag << "i";
return os;
}
};
int main() {
Complex a(1.0, 2.0);
Complex b(3.0, 4.0);
Complex sum = a + b;
Complex product = a * b;
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
std::cout << "a + b = " << sum << std::endl;
std::cout << "a * b = " << product << std::endl;
std::cout << "a == b: " << (a == b) << std::endl;
return 0;
}Last updated