Write a programe to demonstrate the Operator Overloading for any unary and binary operator with expression using both operators together in that expression.
#include <iostream>
using namespace std;
class Distance{
int meters, centimeters;
public:
Distance(int m, int cm): meters(m), centimeters(cm){
while(centimeters >= 100){
centimeters -= 100;
meters += 1;
}
}
void show(){
cout<<meters<<" meters"<<" "<<centimeters<<" centimeters"<<endl;
}
Distance operator-(){
return Distance(this->meters * -1, this->centimeters * -1);
}
Distance operator+(const Distance &other){
return Distance(this->meters + other.meters, this->centimeters + other.centimeters);
}
};
int main(){
Distance distA(4, 4), distB(5, 534);
cout<<"A = ";distA.show();
cout<<"B = ";distB.show();
cout<<"-A + B = "; (-distA + distB).show();
return 0;
}
Comments
Leave a comment