Tuesday, April 28, 2009

Overloading Unary Operator using - Operator

A minus operator, when used as a unary, takes just one operator. We know that this operator used to subtract two values. Consider the program we can subtract two values separately using ‘-’ operator

Example

header files

class minus
{
int a,b,c;
public:
void get();
{
a=10;
b=-20;
z=30;
}
void operator-()
{
a=-a;
b=-b;
c=-c;
}

void display()
{
cout<<"A=" << a <<"\n";
cout<<"B=" << b <<"\n";
cout<<"C=" << c <<"\n";
}
};

void main()
{
clrscr();
minus obj;
obj.get();
obj.display();
-obj;
obj.display();
getch();
}

Output will be

A=-10
B=20
Z=-30

No comments:

Post a Comment