Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type.
This C++ program demonstrates operator overloading using the class Complex, which represents complex numbers with real and imaginary parts.
/* Operator Overloading in C++ 2+5i 3+2i ---- 5+7i */ #include<iostream> using namespace std; class Complex { private: int real,img; public: Complex(){ real=0;img=0;} Complex(int r,int i){ real=r;img=i;} void print() { cout<<real<<" + "<<img<<"i"<<endl; } Complex operator +(Complex c) { Complex temp; temp.real=real+c.real;//2+3 temp.img=img+c.img;//5+2 return temp; } }; int main() { Complex c1(2,5); Complex c2(3,2); Complex c3; c3=c1+c2; c3.print(); return 0; }
5 + 7iTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions