Answer to Question #327120 in C++ for raju

Question #327120

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-13T10:33:13-0400
#include <iostream>

using namespace std;


class Distance
{
	int kiloMtr;
	float metr;
public:
	Distance():kiloMtr(0),metr(0){}
	Distance(int _kiloMtr,	int _metr)
	:kiloMtr(_kiloMtr)
	{
		if (_metr >= 1000)
		{
			kiloMtr += _metr / 1000;
			metr = _metr % 1000;
		}
		else
			metr = _metr;
	}
	void Display()
	{
		cout << "\nInfo about distance: "
			<< "\nKilimeters: " << kiloMtr
		<< "\nMetr: " << metr;
	}
	friend Distance operator+ (Distance& d1, Distance& d2);
};


Distance operator+(Distance& d1, Distance& d2)
{
	int km = d1.kiloMtr + d2.kiloMtr;
	int m = d1.metr + d2.metr;
	return Distance(km, m);
}


class Wage
{
	int kiloGrm;
	float gram;
public:
	Wage():kiloGrm(0),gram(0){}
	Wage(int _kiloGrm, int _gram)
		:kiloGrm(_kiloGrm)
	{
		if (_gram >= 1000)
		{
			kiloGrm += _gram / 1000;
			gram = _gram % 1000;
		}
		else
			gram = _gram;
	}
	Wage operator- (Wage& w)
	{
		int k = kiloGrm - w.kiloGrm;
		int g = gram - w.gram;
		return Wage(k, g);
	}
	void Display()
	{
		cout << "\nInfo about wage: "
			<< "\nKilograms: " << kiloGrm
			<< "\nGrams: " << gram;
	}
};

void main()
{
	Distance d(3, 2500);
	d.Display();
	Wage w(10, 4500);
	w.Display();
	int km, mtr;
	int kg, grm;
	cout << "\nPlease, enter kilometers and meters: ";
	cin >> km >> mtr;
	cout << "Please, enter kilograms and grams: ";
	cin >> kg >> grm;
	Distance d2(km, mtr);
	Distance d3 = d + d2;
	cout << "\nd + d2 = ";
	d3.Display();
	Wage w2(kg, grm);
	Wage w3 = w - w2;
	cout << "\nw - w2 = ";
	w3.Display();


}

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