Answer to Question #189924 in C++ for Fasil Shafi

Question #189924

 Write a programe to demonstrate the Operator Overloading for any unary and binary operator with expression using both operators together in that expression.


1
Expert's answer
2021-05-06T06:54:59-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS