Page 149 - DCAP404 _Object Oriented Programming
P. 149
Object-oriented Programming
Notes void disp(void);
void operator- (); // overload unary operator minus
};
void integer::getdata(int a, int b, int c)
{
x=a; y=b; z=c;
}
void integer::disp(void)
{
cout << x << “ “;
cout<< y<<“ “;
cout<< z<< “\n”;
}
void integer::operator- () // Defining operator- ()
{
x = -x; y = -y; z = -z;
}
void main ()
{
integer S;
S.getdata(11,-21,-31);
Cout<< “S: “;
S.disp();
-S;
cout<<“-S : “;
S.disp();
getch();
}
You should see the following output.
S: 11 -21 -31
-S:-11 21 31
!
Caution The function written to overload the operator is a member function. Hence no
argument is passed to the function. In the main() function, the statement -S invokes the
operator function which negates individual data elements of the object S.
The same program can be rewritten using friend function. This is demonstrated in the following
Program. In this program we define operator function to perform unary subtraction using a
friend function.
142 LOVELY PROFESSIONAL UNIVERSITY