简体   繁体   中英

Double overloading the istream and ostream operators in C++

I have a Fraction class that allows the input of a fraction in the form of c/d. I can output and input fractions just fine, but when I modify them with my custom function, shown down below, it does nothing at all.

I have the following overloaded >> and << operators:

  ostream& operator<<(ostream &out, const Fraction &f)
{
    char x = '/';
    out << f.num;
    out << x;
    out << f.den;
    return out;
}

istream& operator>>(istream &in, Fraction &r)
{
    //in >> r;
    int whole = 0, num, den = 1;
    char next;
    in >> num;
    next = in.peek();
    if(next == '+'){
        in.get();
        whole = num;
        in >> num;
        next = in.peek();
    }
    if(next == '/'){
        in.get();
        in >> den;
    }
    if(whole != 0){
        num += (whole * den);
    }
    if(den == 0){
        den = 1;
    }
    r.num = num;
    r.den = den;

    return in;
}

Furthermore, I have a function that makes two fractions so that they are with the same common denominator:

void setEqualDen(Fraction a, Fraction b){
    int tempa = a.den;
    int tempb = b.den;
    a.den *= tempb;
    b.den *= tempa;
    a.num *= tempb;
    b.num *= tempa;
}

I then try to output the result in the main as so:

setEqualDen(Fa, Fb);
    cout << "The fractions are " << Fa << " , " << Fb <<   
             endl;

This does not work. Is there a necessary step such as double overloading the << and >> operators in C++, or is my syntax simply missing something?

You want the & in the function definition, because you need to pass by reference since you're modifying your `Fractions.

void setEqualDen(Fraction &a, Fraction &b){
    int tempa = a.den;
    int tempb = b.den;
    a.den *= tempb;
    b.den *= tempa;
    a.num *= tempb;
    b.num *= tempa;
}

You need to check for input errors and skip whitespace. I suggest using a temporary for containing the first digit, as it could be either the whole number or the numerator. The differentiating needs to take place after the '/' is detected.

std::istream& operator>>(std::istream& inp, Fraction& f)
{
  int temp = 0;
  f.num = 0;
  f.den = 1;
  inp >> temp;  // Could be whole number or numerator.
  if (inp)
  {
    int whole = temp;
    int numerator = 0;
    inp >> numerator;
    if (!inp)
    {
      // Let's assume that the input failed because of the '/' symbol.
      numerator = temp;
      whole = 0;
      inp.clear();
    }
    else
    {
      inp.ignore(1000, '/'); // Skip over the '/'
    }
    int denominator = 1;
    inp >> denominator;
    if (denominator == 0) denominator = 1;
    numerator += whole * denominator;
    f.num = numerator;
    f.den = denominator;
  }
  return inp;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM