Question: Can you convert my code that currently only works with integers to now work with any type of number such as a float or a
Can you convert my code that currently only works with integers to now work with any type of number such as a float or a double? When converting to a template you may need to move all of your implementation into the .h file.
thank you
#include
using namespace std;
// class definition
template
class fractionType
{
// template class with generic data types
T num, den;
public:
// default constructor
fractionType() {}
// parameterized constructor
fractionType(T a, T b)
{
num = a;
den = b;
}
// overload the stream insertion operators
friend ostream &operator<<(ostream &out, fractionType f)
{
out << f.num << "/" << f.den;
return out;
}
friend istream &operator>>(istream &in, fractionType &f)
{
cout << "Enter numerator: ";
in >> f.num;
cout << "Enter denominator: ";
in >> f.den;
return in;
}
// overlaod the arithmetic operators
friend fractionType operator+(fractionType a, fractionType b)
{
fractionType sum((a.num * b.den + a.den * b.num), (a.den * b.den));
return sum;
}
friend fractionType operator-(fractionType a, fractionType b)
{
fractionType diff((a.num * b.den - a.den * b.num), (a.den * b.den));
return diff;
}
friend fractionType operator*(fractionType a, fractionType b)
{
fractionType res((a.num * b.num), (a.den * b.den));
return res;
}
friend fractionType operator/(fractionType a, fractionType b)
{
fractionType res((a.num / b.den), (a.den * b.num));
return res;
}
// overload the relational operators
friend bool operator<(fractionType a, fractionType b)
{
return a.num * b.den < a.den * b.num;
}
friend bool operator>(fractionType a, fractionType b)
{
return a.num * b.den > a.den * b.num;
}
friend bool operator<=(fractionType a, fractionType b)
{
return a.num * b.den <= a.den * b.num;
}
friend bool operator>=(fractionType a, fractionType b)
{
return a.num * b.den >= a.den * b.num;
}
friend bool operator==(fractionType a, fractionType b)
{
return a.num * b.den == a.den * b.num;
}
};
// small main function to test some operators and functions
int main()
{
fractionType
fractionType
cin >> x;
cin >> y;
fractionType
cout << z;
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
