Posts

Showing posts with the label operator overloading in cpp
 //Program - 5 overload unary -- (minus minus) operator using friend function. #include <iostream.h> #include <conio.h> class test { int a, b; public: test() //default constructor { cout << "Enter value for A = "; cin >> a; cout << "Enter vslue for B = "; cin >> b; } void show() { cout << endl << "A = " << a; cout << endl << "B = " << b; } friend void operator -- (test &) }; void operator -- (test &ref) { -- ref.a; -- ref.b; } void main() { clrscr(); test obj;   //calls Default Constructo --obj;      //call opertor --() friend function obj.show(); getch(); }
 //Program - 4 Overload Binary Operator + (plus) using member function #include <iostream.h> #include <conio.h> class calculate { int a, b; public: void getdata() { cout << "Enter value a = "; cin >> a; cout << "Ente value b = "; cin >> b; } void print() { cout << endl << "A = " << a; cout << endl << "B = " << b; } calculate operator+(calculate ob2) { calculate temp; temp.a = a + ob2.a; temp.b = b + ob2.b; return temp; } }; void main() { clrscr(); calculate obj1, obj2, obj3; obj1.getdata(); obj2.getdata(); obj3 = obj1 + obj2; //calls operator+() fuction obj3.print(); getch(); }
 //Program - 3 -overload Unary operator ~ (bitwise one's complement) using friend function #include <iostream.h> #include <conio.h> class Test { int a, b; public : Test() { cout << " Enter Value a = "; cin >> a; cout << " Enter value b = "; cin >> b; } void show() { cout << endl << "A = " << a; cout << endl << "B = " << b; } friend void operator~(Test &); }; void operator~(Test &ref) { ref.a = ~ref.a; ref.b = ~ref.b; } void main() { clrscr(); Test obj; obj.show(); ~obj; obj.show(); getch(); }
 //Program - 2 : Overload Unary -(minus) operator using member function #include <iostream.h> #include <conio.h> class Number { int a; public : Number() { cout << "Enter value a = "; cin >> a; } void show() { cout << endl << " A = "<< a; } void operator-() {        a = - a; } }; void main() { clrscr(); Number obj; // calls Default constructor obj.show(); -obj; //calls operator-() function obj.show(); getch(); }
 //Program - 1 overload unary operator using member function  program - 1 #include <iostream.h> #include <conio.h> class Number { int a, b; public : Number() //Deafualt Constructor { cout << " Enter value of a : "; cin >> a; cout << " Enter value of b : "; cin >> b; } void display() { cout << endl << "A = " << a; cout << endl << "B = " << b; } void operator++() { ++a; ++b; } }; void main() { clrscr(); Number obj; //calls Deafault constructor obj.display(); ++obj; //calls operator++() function cout << endl << "After ++obj : "; obj.display(); getch(); }