Write a class for Distance which have two parts inches and feet as floating data members. Write an overloaded function for (+) binary operator to add the inches and feet of two distance objects. Main function is also necessary to show the working of the Class.
#include <iostream>
using namespace std;
class Distance {
int feet, inches;
public:
// default constructor
Distance() {
feet = 0;
inches = 0;
}
// parameterized constructor
Distance(int f, int i){
feet = f;
inches = i;
}
void readDistance(); // to read distance
void displpay(); // to display distance
//add two Distance using + operator overloading
Distance operator+(Distance &other) {
Distance otherDistance;
otherDistance.inches = inches + other.inches;
otherDistance.feet = feet + other.feet + (otherDistance.inches/12);
otherDistance.inches = otherDistance.inches%12;
return otherDistance;
}
};
void Distance::readDistance() {
cout << "Enter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
}
void Distance:: displpay() {
cout << "Feet: " << feet << " " << "Inches: " << inches << endl;
}
int main() {
Distance Dist_1, Dist_2, Dist_3;
cout << "Enter first Distance:" << endl;
Dist_1.readDistance();
cout << endl;
cout << "Enter second Distance:" << endl;
Dist_2.readDistance();
cout << endl;
//sum:
Dist_3 = Dist_1 + Dist_2;
cout << "Distance_1 + Distance_2: "<<endl ;
Dist_3.displpay();
cout << endl;
return 0;
}
Comments
Leave a comment