Question#4: Having the class Fraction definition below, do the following: 1- Cha
ID: 3550683 • Letter: Q
Question
Question#4:
Having the class Fraction definition below, do the following:
1- Change the type of the numerator data member to int * numerator ;
2- Define a defaulted constructor to initialize the fraction to 1
3- Define a parameterized constructor that has two integer parameters as
numerator and denominator values.
4- Define a copy constructor to copy the data members successfully.
5- What other functions that should be defined?
#include <iostream>
using namespace std;
class Fraction
{
private:
int numerator ;
int denominator;
public:
void setNumerator( int num)
{
}
void setDenominator(int num)
{
}
int getDenominator()
{
int getNumerator(){return numerator ;}};
numerator=num;
denominator=num;
return denominator;}
Explanation / Answer
//Having the class Fraction definition below, do the following:
#include <iostream>
using namespace std;
class Fraction
{
private:
//1- Change the type of the numerator data member to int * numerator ;
int* numerator ;
int denominator;
public:
//2- Define a defaulted constructor to initialize the fraction to 1
Fraction()
{
numerator = new int;
*numerator = 1;
denominator = 1;
}
//3- Define a parameterized constructor that has two integer parameters as numerator and denominator values.
Fraction(int num, int den)
{
numerator = new int;
setNumerator(num);
setDenominator(den);
}
void setNumerator( int num)
{
*numerator=num;
}
void setDenominator(int num)
{
denominator=num;
}
int getDenominator()
{
return denominator;
}
int getNumerator()
{
return *numerator ;
}
//4- Define a copy constructor to copy the data members successfully.
Fraction(const Fraction& obj)
{
numerator = new int;
setNumerator(*obj.numerator);
setDenominator(obj.denominator);
}
// 5- What other functions that should be defined?
void print()
{
cout <<*numerator << " / " << denominator << endl;
}
};
int main()
{
Fraction F1(3,2);
F1.print();
Fraction F2(F1);
F1.print();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.