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>
#include <string>
using namespace std;
//class named Distance
class Distance {
//variables
private:
//two private data members such as feet(integer),inches(float)
int feet;
float inches;
public:
// one input function to input values to the data members
void input(){
cout<<"Enter feet: ";
cin>>feet;
cout<<"Enter inches: ";
cin>>inches;
// 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.
if(inches>=12){
int feets=inches/12;
inches-=feets*12;
feet+=feets;
}
}
// one Display function to show the distance.
//The distance 5 feet and 6.4 inches should be displayed as 5'- 6.4".
void display(){
cout<<feet<<"'- "<<inches<<"\"\n";
}
//(the + operator should be overloaded).
Distance operator+ (const Distance & otherDistance) const{
Distance distance;
distance.feet=this->feet+otherDistance.feet;
distance.inches=this->inches+otherDistance.inches;
if(inches>=12){
int feets=inches/12;
distance.inches-=feets*12;
distance.feet+=feets;
}
return distance;
}
};
int main () {
//Then add the two objects of Distance class and then display the result
cout<<"Distance 1: \n";
Distance distance1;
distance1.input();
cout<<"\n\nDistance 2: \n";
Distance distance2;
distance2.input();
cout<<"\n\nDistance 1:\n";
distance1.display();
cout<<"\nDistance 2: \n";
distance2.display();
Distance sum=distance1+distance2;
cout<<"\nDistance sum: ";
sum.display();
//Delay
system("pause");
return 0;
}
Comments
Leave a comment