i need to create a class named rational, and i need to have the integer variables denominator and numerator in private. The i need to provide a constructor that enables an object of the class to be initialized when it is declared. then it says the constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. so 2/4 should be stored in the object as 1 in the numerator, and 2 in the denominator. heres what i have done so far, im really confused.

#include <iostream>

class rational {

public:






private:

int numerator;
int denominator;


}; // end of rational class

int main()
{











return 0;
}

Recommended Answers

All 2 Replies

For starters, you'll need 2 constructors. One will be something like

rational(int m, int n)
{  num = m;
    den = n; //You really should check for n == 0
}

and the other (the default) would be

rational()
{  num = 0;
    den = 1;
}

In order to do the reduced form (i.e., 1/2 instad of 2/4) you'll need t owrite a program for the Euclidian (gcd) algorithm, or get it from somewhere.

For starters, you'll need 2 constructors. One will be something like

rational(int m, int n)
{  num = m;
    den = n; //You really should check for n == 0
}

and the other (the default) would be

rational()
{  num = 0;
    den = 1;
}

This could also be done like this.

class rational
{
   int numerator, denominator;
public:
   rational(int n = 0, int d = 1) : numerator(n), denominator(d)
   {
      // additional code
   }
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.