Write a program in C++ to implement the concept of unary operator overloading.
Algorithm to solve the above problem:
1. Start the Program
2. Create a class named space and declare necessary data members and member functions and operator function as member function
3. The operator unary minus is overloaded to perform the operation of changing sign
4. Define member function getdata(), to get three values that is passed as arguments.
5. The operator function is defined where the sign of values is changed.
6. Function display() is defined where the values is displayed before and after sign change.
7. Stop the program.
Implementation of the above problem in C++:
#include<iostream>
using namespace std;
class space
{
int x,y,z;
public:
void getdata(int a,int b,int c);
void display(void);
void operator-();
};
void space::getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space::display(void)
{
cout<<x<<" ";
cout<<y<<" ";
cout<<z<<"\n";
}
void space::operator-()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
space s;
s.getdata(1,-2,3);
cout<<"s:";
s.display();
-s;
cout<<"s:";
s.display();
return 0;
}
The output of the above program is tested on www.jdoodle.com
Output:
s:100 -200 300
s:-100 200 -300
Thanks
Mukesh Rajput
Post A Comment:
0 comments: