Saturday 17 September 2011

Unary operator overloading


Unary operator overloading
Aim:
To write a C++ program for unary operator overloading.
Algorithm:
Step 1: Declare the class as count.
Step 2: Declare the data member as c.
Step 3: Declare the member function as
count( )
void operator ++( )
int getcount( )
Step 4: count() function is used to initialize the  “c” value to zero.
Step 5: getcount() function returns the value of c.
Step 6: operator ++()  function is used to increment the value.
Step 7: In the main, create the object for the class count.
Step 8: Unary operator function is called by using the syntax operator objectname.
Step 9: Display the value of c using getcount() function.

Program:
#include<iostream.h>
#include<conio.h>
class count
{
int c;
public:
count()
{
c=0;
}
void operator ++()
{
c=c+1;
}
int getcount()
{
return(c);
}
};

void main()
{
clrscr();
count c1,c2;
cout<<"\nThe value of c in c1="<<c1.getcount();
cout<<"\nThe value of c in c2="<<c2.getcount();
++c1;
++c2;
++c2;
cout<<"\nThe value of c in c1="<<c1.getcount();
cout<<"\nThe value of c in c2="<<c2.getcount();
}

Output:
The value of c in c1=0
The value of c in c2=0
The value of c in c1=1
The value of c in c2=2

0 comments:

Post a Comment