The code below is a book example that adds two fractions and prints out a message when the copy constructor is executed.

The end of the chapter they show a way to initialize a Fraction object from a string.Code:#include <iostream> #include <cstdlib> using namespace std; class Fraction { private: int num, den; // Numerator and denominator. public: Fraction() {set(0, 1);} Fraction(int n, int d) {set(n, d);} Fraction(Fraction const &src); void set(int n, int d) {num = n; den = d; normalize();} int get_num() {return num;} int get_den() {return den;} Fraction add(Fraction other); Fraction mult(Fraction other); private: void normalize(); // Put fraction into standard form. int gcf(int a, int b); // Greatest Common Factor. int lcm(int a, int b); // Lowest Common Denominator. }; int main() { Fraction f1(3, 4); Fraction f2(f1); Fraction f3 = f1.add(f2); cout << "The value of f3 is "; cout << f3.get_num() << "/"; cout << f3.get_den() << endl; system("PAUSE"); return 0; } // --------------------------------------------------- // FRACTION CLASS FUNCTIONS Fraction::Fraction(Fraction const &src) { cout << "Now executing copy constructor." << endl; num = src.num; den = src.den; } // Normalize: put fraction into a standard form, unique // for each mathematically different value. // void Fraction::normalize(){ // Handle cases involving 0 if (den == 0 || num == 0) { num = 0; den = 1; } // Put neg. sign in numerator only. if (den < 0) { num *= -1; den *= -1; } // Factor out GCF from numerator and denominator. int n = gcf(num, den); num = num / n; den = den / n; } // Greatest Common Factor // int Fraction::gcf(int a, int b) { if (a % b == 0) return abs(b); else return gcf(b, a % b); } // Lowest Common Multiple // int Fraction::lcm(int a, int b){ return (a / gcf(a, b)) * b; } Fraction Fraction::add(Fraction other) { Fraction fract; int lcd = lcm(den, other.den); int quot1 = lcd/den; int quot2 = lcd/other.den; fract.set(num * quot1 + other.num * quot2, lcd); fract.normalize(); return fract; } Fraction Fraction::mult(Fraction other) { Fraction fract; fract.set(num * other.num, den * other.den); fract.normalize(); return fract; }

Example:

Then the funtionCode:Fraction a = "1/2" , b = "1/3"; They suggest this string Fraction arr_of_fract[4] = {"1/2" , "1/3" , "3/4"}; we need to declare within the fraction class declaration: Fraction (char *s);

Any ideas on how to implement this?Code:Fraction::Fraction(char *s) { int n = 0; int d = 1; char *p1 = strtok(s, "/, "); char *p2 = strtok(NULL, "/, "); if (p1 != NULL) n = atoi(p1); if (p2 != NULL) d = atoi(p2); set(n,d); }