conversions: objects to basic types/vice versa
im following a book that has an example of converting objects to basic types and vice versa. ive checked the code numerous times but i get a different output than what the book is saying. in this case im trying to convert Distance (feet and inches) into meters and vice versa.
Code:
books output:
1: 7 feet 8.51949 inches
1: 2.35 meters
2: 1.78435 meters
my output:
1: 7 feet 8.51949 inches
1: 2.35 meters
2: -2.92738 meters
--------------------------------------
#include<iostream>
using namespace std;
////////////////////////////////////
class Distance //english Distance class
{
private:
const float MTF; //meters to feet
int feet;
float inches;
public:
Distance() : feet(0), inches (0.0), MTF(3.280833F)
{ }
Distance(float meters): MTF(3.280833F) //convert meters to Distance
{
float fltfeet = MTF * meters; //convert float to feet
feet = int(fltfeet); //feet is the integer part so strip it
inches = 12 * (fltfeet - feet); //inches is whats left
}
Distance(int ft,float in) : feet(ft),inches(in)
{ }
void getdist() //get length from user
{
cout << "enter feet: "; cin >> feet;
cout << "enter inches: "; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << " feet " << inches << " inches" << endl; }
operator float() const //conversion operator
{ //converts Distance to meters
float fracfeet = inches / 12; //convert the inches
fracfeet += static_cast<float>(feet); //add the feet
return fracfeet/MTF;
}
};
//////////////////////////////////////
int main()
{
float mtrs;
Distance dist1 = 2.35F; //one arg constructor convert meters to Distance
cout << "1: "; dist1.showdist();
mtrs = static_cast<float>(dist1); //USES CONVERSION operator for distance to meters
cout << "\n1: " << mtrs << endl;
Distance dist2(5, 10.25);
mtrs = dist2; //also uses conversion operator
cout << "\n2: " << mtrs << endl;
// dist2 = mtrs; //WRONG: '=' wont convert
return 0;
}
for the last value it always turns up negative for me. why is that?