Question: Create an overloaded constructor that takes as an argument a string.The string is going to contain the fraction your going to have to parse. Have

Create an overloaded constructor that takes as an argument a string.The string is going to contain the fraction your going to have to parse. Have the number and denominator separated by one space, Ex: 1 2

//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);

};

#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);

}

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 * den;

return tmp;

}

Fraction Fraction::sub(const Fraction &f)

{

Fraction tmp;

tmp.num = (this->num * f.den) - (f.num * f.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;

//in case of inversion

if(tmp.den < 0)

{

tmp.den *= -1;

tmp.num *= -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;

f3 = f1.mult(f2);

f3.printFraction();

return 0;

}

/* current output

1/8

Press any key to continue . . .

*/

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!