In C ++ :DistanceCreate the class represented in this Distance class diagramView
ID: 3761269 • Letter: I
Question
In C ++ :DistanceCreate the class represented in this Distance class diagramView feet:int - inches:int + Distance() + Distance( ft:int , in:int ) + getFeet():int + setFeet( ft:int ):void + getInches():int + setInches( in:int):void + totalInches():int + showDistance():void + operator==( dist:Distance& ):bool + operator+( dist:Distance& ):Distance + operator-( dist:Distance& ):Distancein a new window. Test the class to make sure all functions work as intended. Replace the equals(), add() and sub() functions with the corresponding operator functions. Test the class to ensure all overloaded operators work as intended.
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
class Distance
{
private:
double inches;
int feet;
public:
Distance();
Distance( int ft = 3 , double in = 6 );
void setInches(double in);
double getInches();
void setFeet(int ft);
int getFeet();
bool operator==(Distance& dist);
Distance operator+(Distance& dist);
Distance operator-(Distance& dist);
Distance operator*(Distance& dist);
void qualifyValues();
string showDistance();
double getTotalInches();
};
ostream& operator<<(ostream& out, const Distance& dist)
{
cout << dist.feet << ''' << dist.inches << '"' << endl;
cout << ''' << '"' << endl;
return out;
}
istream& operator>>(istream& in, Distance& dist)
{
return in;
}
Distance::Distance()
{
feet = 4;
inches = 5;
qualifyValues();
}
Distance::Distance(int ft, double in)
{
feet = ft;
inches = in;
qualifyValues();
}
void Distance::setInches(double in)
{
inches = in;
}
double Distance::getInches()
{
return inches;
}
void Distance::setFeet(int ft)
{
feet = ft;
}
int Distance::getFeet()
{
return feet;
}
bool Distance::operator==(Distance& dist)
{
if (dist.feet == feet && dist.inches == inches)
return true;
else
return false;
}
Distance Distance::operator+(Distance& dist)
{
int ft = feet + dist.feet;
double in = inches + dist.inches;
return Distance(ft, in);
}
Distance Distance::operator-(Distance& dist)
{
int ft = feet - dist.feet;
double in = inches - dist.inches;
while (in < 0)
{
if (ft < 0)
{
//cout << "ERROR: Negative Distance!" << endl;
}
ft = ft - 1;
in = in + 12;
}
return Distance(ft, in);
}
Distance Distance::operator*(Distance& dist)
{
double in;
in = this->getTotalInches();
in = in * dist.getTotalInches();
return Distance(0, in);
}
void Distance::qualifyValues()
{
if (feet == 0 && inches == 0)
{
cout << "Invalid Distance Parameters, Enter valid values: " << endl;
//cin >> this;
// this is a pointer, use cin >> feet; and cin >> inches instead
}
while (inches >= 12)
{
feet++;
inches -= 12;
}
}
string Distance::showDistance()
{
string a;
return a;
}
double Distance::getTotalInches()
{
double in;
in = feet * 12;
in += inches;
return in;
}