Question: C++: For an assignment, we are supposed to take the finished code and create an overloaded constructor that takes as an argument a string. The
C++:For an assignment, we are supposed to take the finished code and create an overloaded constructor that takes as an argument a string. The string will contain a fraction, which needs to be parsed. My professor said that the string can be as simple as "1 2", with the space between the two, with the numbers being the numerator and the denominator respectively. Here is the code it needs to be built upon:
fraction.h
#ifndef FRACTION
#define FRACTION
class Fraction
{
private:
int num;
int den;
public:
void setFraction(int n, int d);
Fraction add(const Fraction &f);
Fraction sub(const Fraction &f);
Fraction mult(const Fraction &f);
Fraction div(const Fraction &f);
void printFraction();
//Constructors
Fraction();
Fraction(int num, int den);
Fraction(int num, int den, string frac);
};
#endif
fraction.cpp
#include
#include "fraction.h"
using namespace std;
Fraction::Fraction()
{
this->setFraction(1, 1);
}
Fraction::Fraction(int num, int den)
{
this->setFraction(num, den);
}
Fraction::Fraction(int num, int den, string frac)
{
this->setFraction(num, den);
}
void Fraction::setFraction(int n, int d)
{
this->num = n;
this->den = d;
}
Fraction Fraction::add(const Fraction &f)
{
Fraction tmp;
tmp.num = (this->num * f.den) + (f.num * this->den);
tmp.den = f.den * this->den;
return tmp;
}
Fraction Fraction::sub(const Fraction &f)
{
Fraction tmp;
tmp.num = (this->num * f.den) - (f.num * den);
tmp.den = f.den * this->den;
return tmp;
}
Fraction Fraction::mult(const Fraction &f)
{
Fraction tmp;
tmp.num = this->num * f.num;
tmp.den = this->den * f.den;
return tmp;
}
Fraction Fraction::div(const Fraction &f)
{
Fraction tmp;
tmp.num = this->num *f.den;
tmp.den = this->den * f.num;
if (tmp.den < 0)
{
tmp.num *= -1;
tmp.den *= -1;
}
return tmp;
}
void Fraction::printFraction()
{
cout << this->num << "/" << this->den << endl;
}
main.cpp
#include
#include "fraction.h"
using namespace std;
int main()
{
Fraction f1(1, 4), f2(1, 2), f3, f4, f5, f6;
f3 = f1.add(f2);
f4 = f1.sub(f2);
f5 = f1.mult(f2);
f6 = f1.div(f2);
f3.printFraction();
f4.printFraction();
f5.printFraction();
f6.printFraction();
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
To complete your assignment by creating an overloaded constructor that takes a string representing a fraction we need to parse that string to extract ... View full answer
Get step-by-step solutions from verified subject matter experts
