gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
write a program to perform all operator overloading
- User
write a program to perform all operator overloading
- Assistant
Here is an example of a program that demonstrates operator overloading for various operators in C++:
#include<iostream> using namespace std; class Complex { private: float real; float imag; public: Complex(float r = 0.0, float i = 0.0) { real = r; imag = i; } Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } Complex operator - (Complex const &obj) { Complex res; res.real = real - obj.real; res.imag = imag - obj.imag; return res; } Complex operator * (Complex const &obj) { Complex res; res.real = real * obj.real - imag * obj.imag; res.imag = real * obj.imag + imag * obj.real; return res; } Complex operator / (Complex const &obj) { Complex res; float denominator = obj.real * obj.real + obj.imag * obj.imag; res.real = (real * obj.real + imag * obj.imag) / denominator; res.imag = (imag * obj.real - real * obj.imag) / denominator; return res; } void display() { cout << real << " + " << imag << "i" << endl; } }; int main() { Complex c1(3.0, 2.0), c2(1.0, 7.0); Complex sum = c1 + c2; Complex diff = c1 - c2; Complex prod = c1 * c2; Complex div = c1 / c2; cout << "Sum of c1 and c2: "; sum.display(); cout << "Difference of c1 and c2: "; diff.display(); cout << "Product of c1 and c2: "; prod.display(); cout << "Division of c1 and c2: "; div.display(); return 0; }