The program contains a class complex with two member variables x and y and a string class with one member variable. Two objects are created for complex class and string class and accepted values through read () function and their values are added using the operator overloaded function and assigned to the third object for each class. Values of the added object are displayed using the display () function. The + operator is overloaded here.
#include<iostream.h> #include<string.h> #include<conio.h> class number { private: int num1,num2; public: void input() { cout<<"nntEnter the real part:"; cin>>num1; cout<<"ntEnter the imaginary part:"; cin>>num2; cout<<"n"; } number operator + (number x) /*Operator overloading*/ { number temp; temp.num1 = num1 + x.num1; temp.num2 = num2 + x.num2; return(temp); } void display() { cout<<"nntSum of two numbers is: "<<num1<<" + i "<<num2; } };
Output
First Number
Enter the real part: 5
Enter the imaginary part: 4Second Number
Enter the real part: 1
Enter the imaginary part: 2Sum of 2 no is : 6 + i 6
Pingback: C++ program to add two complex nos. | Coderz Heaven | Internet blog