learn me operator overloading step by step in c++ with examples
Operator overloading in C++ allows us to new meanings for the standard operators, such as +, -, *, or /, for our own custom classes. Here's a step-by-step guide on how to use operator overloading in C++ with examples:
Choose the Operator:
Create a Class:
class Complex { private: double real; double imag; public: Complex(double r, double i) : real(r), imag(i) {} // Other member functions and constructors };
Overload the Operator:
class Complex { public: Complex operator+(const Complex& c) { return Complex(real + c.real, imag + c.imag); } };
Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); }
Use the Operator:
Complex c1(3.0, 4.0); Complex c2(1.0, 2.0); Complex sum1 = c1 + c2; // Using member function Complex sum2 = operator+(c1, c2); // Using global function
Additional Considerations:
Remember that overloading operators should be done with caution and in a way that makes sense for the class you are working with. Overloading operators can make the code concise and readable, but it should also be intuitive and follow the principle of least astonishment.
By following these steps, you can effectively use operator overloading in C++ to define custom behavior for operators in your classes.
how do you print sum1?
To print the sum1
object in C++, you can the stream insertion operator <<
for your Complex
class. Here's how can achieve this:
class Complex { public: // Other member functions and constructors friend std::ostream& operator<<(std::ostream& os, const Complex& c) { os << c.real << " + " << c.imag <<i"; return os; } };
By overloading the <<
as a friend function inside the Complex
class, you can now use the <<
operator to print sum1
and other `Complex objects:
std::cout << "Sum1 " << sum1 << std::endl;
provide the full code
Certainly! Here's the complete code that demonstrates the operator over for the Complex class in C++:
#include <iostream> class Complex { private: double real; double imag; public: Complex(double r, double i) : real(r), imag(i) {} Complex operatorconst Complex& c) { return Complex(real + c.real, imag + c.imag); friend std::ostream& operator<<(std::ostream&, const Complex& c) { os << c.real << " + " << c.imag << "i"; return os; } }; int main() { Complex c13.0, 4.0); Complex c2(1.0 2.0); Complex sum1 = c1 + c2; std::cout << "Sum1: " << sum << std::endl; return 0; }
In this code, we've defined the class with a constructor, an overloaded +
operator, and an overloaded <<
operator (as a friend function). The main function creates two Complex objects, adds them using the overloaded +
operator, and then prints the result using the overloaded <<
operator.