从'int'类型的表达式获取类型'std :: istream&'的引用的无效初始化

Goo*_*ose -1 c++ compiler-errors istream

我正在尝试创建一个使用有理数字并对它们执行运算符重载的类.我在程序的一部分,即输入流上遇到问题.

例如,我应该以"12/8"格式输入,它应该将12存储到变量a中,然后将8存储到变量b中.

这是我的代码:

istream& operator>>( istream& In, Rational& Item )
{
    char division_sign;
    int a,b;

    In >> a >> division_sign;
    if (division_sign != '/' || !In.good())
    {
        In.setstate( ios::failbit );
    }
    else
    {
        In >> b;
        if (b != 0 || !In.good())
        {
        return Item.numerator_ = a, Item.denominator_ = b;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误:

In function 'std::istream& operator>>(std::istream&, Rational&)':
131: error: invalid initialization of reference of type 'std::istream&' from expression of type 'int'
Run Code Online (Sandbox Code Playgroud)

Line 131return声明

moo*_*eep 5

您观察到的编译错误是由于您尝试返回另一种类型的值,因为您已将其放入声明中.你需要返回In而不是b:

return In; 
Run Code Online (Sandbox Code Playgroud)

因此,您应该istream在函数执行路径的任何可能的分支中返回对象引用.也就是说,只将一个这样的return语句放到函数的末尾.

另请参阅有关运算符重载的常见问题解答.