Question
I need to write a c++ program that has a fraction class. It needs to have a constructor with two arguments which default to (0,1). I'm having trouble understanding what a constructor is and I've written my program without it. When I compile it says there is an error because my two terms nume and denom or private. I need to write a c++ program that has a fraction class. It needs to have a constructor with two arguments which default to (0,1). I'm having trouble understanding what a constructor is and I've written my program without it. When I compile it says there is an error because my two terms nume and denom or private.
Explanation / Answer
// This declares a dependency on the system module, iostream. Specifically, this code uses the // system provided objects, cout, and cin, for output and input. #include // This says if the compiler cannot find a symbol, it should try looking in the namespace, std. using namespace std; // This defines a type called, Fraction. class Fraction { private: // This declares two private member variables, num, and den, presumably representing the // numerator and denominator of a fraction. Each object of type Fraction will have its own // num and den. Because they are private they cannot be accidentally modified outside the // definition of Fraction. They are the module's secret. int num, den; public: // This declares a constructor. It uses the default argument notation to actually define // three constructor syntaxes. Two arguments may be given, one, or zero. Fraction() = 1/2, // Fraction(x) = x/2, and Fraction(x, y) = x/y. A default denominator of 1 would be more // normal, especially since this constructor can be used to implicitly convert an int into // a Fraction. Fraction(int n = 1, int d = 2) : num(n), den(d) { } // This function outputs a representation of a Fraction to cout. It repeats the definition // of operator