Pointer data member

أنشِئ Class :

اسمه:  Fraction

المتغيرات : *numerator و  denominator

:يحوي   Parameterized constructor  و Copy constructor و Default constructor

قم بفصل الـ Class interface  في header file و Class implementation في cpp file

لهدف من السؤال هو كيفية التعامل مع الـ pointer في constructors , destructor , set & get  .

الحل:

//.h
class Fraction
{
 int *numerator; //pointer data member
 int denominator;

public:

 Fraction(); //Default constructor
 Fraction(int, int);//Parameterized constructor 
 Fraction(const Fraction &);// Copy constructor 
 ~Fraction();//destructor

 void setNumerator(int);
 void setDenominator(int);

 int getDenominator();
 int getNumerator();

};
------------------------------------------------------
//.cpp
#include <iostream>
#include "Fraction.h"
using namespace std;

//Default constructor
Fraction::Fraction()
{
 numerator = new int; //allocate pointer
 if (!numerator) { cout << "Allocation failure"; exit(1); } //if not allocate
 //initialize
 setNumerator(1);
 setDenominator(1);
}

//Parameterized constructor
Fraction::Fraction(int N, int D)
{
 setNumerator(N); setDenominator(D);
}

//Copy constructor
Fraction::Fraction(const Fraction &obj)
{ numerator = new int; //allocate the pointer for the new object 
if (!numerator) { cout << "Allocation failure"; exit(1); } //if not allocte

//copy information
setNumerator(*obj.numerator); //use '*' to copy the value 
setDenominator(obj.denominator); }

//destructor
Fraction::~Fraction()
{ delete numerator; //delete pointer
}

void Fraction::setNumerator(int num)
{//use '*'
 *numerator = num; 
}
void Fraction::setDenominator(int num){ denominator = num; }

int Fraction::getDenominator(){ return denominator; }

int Fraction::getNumerator()
{ //use '*'
 return *numerator; 
}

Advertisements