The unary operatpr need only one operand.To overload + or - we need only one object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//uniary operator overloading | |
#include<iostream> | |
using namespace std; | |
class Negative | |
{ | |
private: | |
int num; | |
public: | |
Negative(){} | |
Negative(int n)//Constructor | |
{ | |
num=n; | |
} | |
void GetNum(int x) | |
{ | |
num=x; | |
} | |
void print(){ | |
cout<<"Number is "<<num<<endl; | |
} | |
void operator -();//Operator overload | |
}; | |
void Negative :: operator-()// operator overload definition | |
{ | |
num=-num; | |
} | |
int main() | |
{ | |
Negative n1,n2; | |
n1.GetNum(5); | |
n1.print(); | |
-n1; | |
n1.print(); | |
return 0; | |
} |
Number is 5 Number is -5
0 Comments
If you have any doubt and suggestion Please let me know