Answer to Question #326285 in C++ for Daredav

Question #326285

Write a program to overload binary + operator using friend function to add values entered in kilo meters and meters and to overload binary – operator using member function to subtract values entered in kilograms and grams

1
Expert's answer
2022-04-09T17:53:12-0400
#include <iostream>
using namespace std;


class Distance {
    int kilometers;
    int meters;
public:
    Distance(int m=0) {
        kilometers = m / 1000;
        meters = m % 1000;
    }
    Distance(int km, int m) {
        kilometers = km;
        kilometers += m / 1000;
        meters = m % 1000;
    }
    void print() const {
        cout << kilometers << "km "
             << meters << "m";
    }
    friend Distance operator+(const Distance&, int);
};



class Weight {
    int kilograms;
    int grams;
public:
    Weight(int g=0) {
        kilograms = g / 1000;
        grams = g % 1000;
    }
    Weight(int kg, int g) {
        kilograms = kg;
        kilograms += g / 1000;
        grams = g % 1000;
    }
    Weight operator-(int) const;
    void print() const {
        cout << kilograms << "kg "
             << grams << "g";
    }
};


Distance operator+(const Distance& d, int m) {
    int dist = d.kilometers*1000 + d.meters + m;
    return Distance(dist);
}


Weight Weight::operator-(int g) const {
    int weight = kilograms*1000 + grams - g;
    return Weight(weight);
}


int main() {
    Distance d(12, 345);
    Distance new_dist = d + 678;
    d.print();
    cout << " + 678m = ";
    new_dist.print();
    cout << endl;

    Weight w(9, 876);
    Weight new_weight = w - 543;
    w.print();
    cout << " - 543g = ";
    new_weight.print();
    cout << endl;

    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