Here we have shown you the example of operator overloading in unary operator (-) in Prefix and Postfix both form. And we have decremented the values of different objects directly through operator overloading.
//Operator overloading in Unary Operator
#include<iostream>
using namespace std;
class complex{
private:
int real,imaginary;
public:
complex(){ //Default constructor
real=0;
imaginary=0;
}
complex(int r, int i){ //Parameterizeed Constructor
real=r;
imaginary=i;
}
void display(){
cout<< "The real part is: " <<real <<endl;
cout<< "The imaginary part is: " <<imaginary <<"i" <<endl;
}
void operator --(){ //operator overloading function : prefix decrement
real=--real;
imaginary=--imaginary;
}
void operator --(int){ //postfix decrement
real=real--;
imaginary=imaginary--;
}
};
int main(){
complex c1(5,7), c2(10,11); //Object creation and passing arguments to constructors
//Prefix
cout<<"Before pre decrement: " <<endl;
c1.display();
--c1; //Decrementing value of object c1 through operator overloading
cout<<endl <<"After pre decrement: " <<endl;
c1.display();
//Postifix
cout<<endl <<"Before Post decrement: " <<endl;
c2.display();
--c2; //Decrementing value of object c2 through operator overloading
cout<<endl <<"After Post decrement: " <<endl;
c2.display();
return 0;
}
Output:
You have to use (int) while working with unary operators for postfix.
0 comments:
Post a Comment