let's we have a class named Distance having two private data members such as feet(integer), inches(float), one input function to input values to the data members, one Display function to show the distance. The distance 5 feet and 6.4 inches should be displayed as 5’- 6.4”. Then add the two objects of Distance class and then display the result (the + operator should be overloaded). You should also take care of inches if it's more than 12 then the inches should be decremented by 12 and feet to be incremented by 1.
#include <iostream>
using namespace std;
class Distance {
private:
int feet;
float inches;
public:
void input(){
cout<<"Input feet: ";
cin>>feet;
cout<<"Input inches: ";
cin>>inches;
if(inches>=12){
int f=int(inches/12);
inches-=f*12;
feet+=f;
}
}
void display(){
cout<<feet<<"'- "<<inches<<"\"\n";
}
Distance operator+ (const Distance & other) const{
Distance d;
d.feet=this->feet+other.feet;
d.inches=this->inches+other.inches;
if(d.inches>=12){
int f=int(d.inches/12);
d.inches-=f*12;
d.feet+=f;
}
return d;
}
};
int main () {
Distance d1;
Distance d2;
cout<<"Distance 1: \n";
d1.input();
cout<<"\nDistance 2: \n";
d2.input();
cout<<"\n\nDistance 1: ";
d1.display();
cout<<"Distance 2: ";
d2.display();
Distance sum=d1+d2;
cout<<"Sum: ";
sum.display();
system("pause");
return 0;
}
Comments
Leave a comment