簡體   English   中英

在C ++中雙重重載istream和ostream運算符

[英]Double overloading the istream and ostream operators in C++

我有一個分數類,允許以c / d的形式輸入分數。 我可以很好地輸出和輸入分數,但是當使用下面顯示的自定義函數修改分數時,它什么也沒做。

我有以下重載>>和<<運算符:

  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;
}

此外,我有一個函數可以將兩個分數相乘,使它們具有相同的公分母:

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;
}

然后,我嘗試將結果輸出到主目錄中,如下所示:

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

這是行不通的。 是否有必要的步驟,例如在C ++中雙重重載<<和>>運算符,還是我的語法只是缺少某些內容?

您需要在函數定義中使用& ,因為在修改`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;
}

您需要檢查輸入錯誤並跳過空格。 我建議使用一個臨時字符來包含第一個數字,因為它可以是整數或分子。 檢測到“ /”后需要進行區分。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM