Object Oriented Programming with C++

Post on 11-Apr-2017

21 views 0 download

transcript

Object Oriented Programming With C++

void Swap(int a,int b) { a=a+b; b=a-b; a=a-b; cout<<a; cout<<b; }

Q.1 Swap two number     without using third variable ?

void main() {  clrscr(); int a,b; cout<<"Enter two numbers:"; cin>>a>>b; Swap(a,b); getch(); }

Output: enter two numbers 10 12 12 10

Write a C++ program to perform Unary Operator Overloading on minus('-') operator. Ans:      #include<iostream.h>              #include<conio.h>              class abc              {               public:               int a,b,c;

abc() {   } abc(int x,int y,int z) { a=x; b=y; c=z; }

void display() { cout<<a; cout<<b; cout<<c; } void  operator -() { a=-a;

b=-b; c=-c; } }; void main() { clrscr(); abc a1(10,20,30); a1.display();

-a1; a1.display(); getch(); } Output: 10               20               30               -10               -20               -30

Q.2 Write a C++ program operator                overloading for operator '++' to            increase the value for object        using member function. Ans: # include<iostream.h>         # include<conio.h>         class abc         {          int a,b,c;  

abc(); {    } abc ( int x,int y,int z) { a=x; b=y; c=z; }

void display() { cout<<a; cout<<b; cout<<c; } void operator ++() {

void display() { cout<<a; cout<<b; cout<<c; } void operator ++() {

a= ++a; b= ++b; c= ++c; } }; void main() { clrscr();

abc a1(10,20,30); a1.display(); ++a1; a1.display(); getch(); } Output:               10 20 30               11  21  31

Write a C++ program using Unary operator using friend function Ans:         # include <iostream.h>         # include <conio.h>          class inc          {           public:

int a,b,c; public: inc () {   } inc (int x,int y,int z) { a=x; b=y;

c= z; } void display() { cout<<a; cout<<b; cout<<c; }

friend void operator +(inc &i); }; void operator +(inc &i) { i.a=+i.a; cout<<i.a; i.b=+i.b; cout<<i.b;

i.c=+i.c; cout<<i.c; } void main() { clrscr(); inc.c1(10,20,30); inc.c2;

c1.display(); c2+c1; c2.display(); c1.display(); getch(); }

output: 10               20               30               20              40              60

        garbage value            10            20            30