2015-02-24 47 views
0

我有一个分数类,允许以c/d格式输入分数。 我可以输出和输入分数就好了,但是当我用我的自定义函数修改它们时,如下所示,它什么都不做。在C++中双重载入istream和ostream运算符

我有以下重载>>和< <运算符:

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++中的<和>>操作符,还是我的语法只是缺少一些东西?

+2

你是什么意思*不起作用*?如果你的意思是结果不符合你的期望,那么这是因为'setEqualDen'复制了它的参数,而不是通过引用来引用它们。如果这不是问题,那么请解释* double overload *的含义,并发布错误消息,预期输出等。 – Praetorian 2015-02-24 00:04:46

+0

您的输入函数失败,并显示“1 +/25”。 – 2015-02-24 00:12:09

+0

而不是假设空白的数量,你应该跳过它。 – 2015-02-24 00:13:47

回答

2

您希望&在函数定义中,因为您需要通过引用来传递,因为您正在修改“分数”。

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

这可能会解决OP的问题,但没有理由让'setEqualDen'成为一个成员函数,因为它没有访问它被调用的实例。 – Praetorian 2015-02-24 00:12:12

+0

这是给我一个错误,当试图调用函数... – JCoder 2015-02-24 00:16:36

+0

@Praetorian - 是的,这是一个很好的观点,这是没有必要的。这里的偏好是什么,因为函数只对这个特定类有效?我会说让它成为一个成员,这样你就可以移动这个类,而不用担心在另一个程序中重新创建函数。 – TriHard8 2015-02-24 00:17:25

0

您需要检查输入错误并跳过空格。我建议使用临时的第一位数字,因为它可能是整数或分子。在检测到“/”之后需要进行区分。

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