繁体   English   中英

(C++) 我的重载运算符函数都返回错误,尽管它们是朋友,但它们必须是一元或二元的

[英](C++) My overloaded operator functions are all returning the error that they must be unary or binary despite being friends

我的分数类重载运算符不会编译,说它们必须是一元或二元运算符。 (c++) 四处搜索后,我发现让他们成为朋友会删除隐含的第一项的建议,但我的运算符一直是朋友,但仍然返回“错误:重载的'运算符-'必须是一元或二元运算符(有 3 个参数)”,当我去编译。

他们在我的头文件中

friend std::ostream& operator<<(std::ostream& os, const Fraction& frac); //printing
friend std::istream& operator>>( std::istream& is, Fraction& frac); // reading
friend const Fraction operator+(const Fraction& x, const Fraction& y); // adding
friend const Fraction operator-(const Fraction& x, const Fraction& y); // subtract

这是每个的定义

std::ostream& Fraction::operator<<(std::ostream& os, const Fraction& frac) //printing
{
    if(num % den == 0)
        cout << num/den << endl;
    else
        cout << num << "/" << den << endl;
}

std::istream& Fraction::operator>>( std::istream& is, Fraction& frac) // reading
{
    int pc; //peek character

    is >> skipws >> num; // read numerator, skipping whitespace

    pc = is.peek(); // check next character

    if( is && isspace(pc))  //if whitespace after the numerator
    {
        while( is && isspace(pc))
        {
            is.get(); // eat space
            pc = is.peek(); // move through the stream
        }
    }
    else if( is && pc == '/')
    {
        is.get(); // eat the '/'
        is >> skipws >> den;
    }

    if(den == 0)
    {
        throw invalid_argument("denominator is zero");
    }

    if(den < 0)
    {
        num = num * -1;
        den = den * -1;
    }
}

const Fraction Fraction::operator+(const Fraction& x, const Fraction& y) // adding
{
    Fraction temp1;
    Fraction temp2;
    if(x.getden() == y.getden())
    {
        temp1.set(x.getnum() + y.getnum(), x.getden() );
    }
    else
    {
        temp1.set(x.getnum() * y.getden(), x.getden() * y.getden());
        temp2.set(y.getnum() * x.getden(), y.getden() * x.getden());
        temp1.set(temp1.getnum() + temp2.getnum(), temp1.getden());
    }
    reduceFrac(temp1);
    return temp1;
}

const Fraction Fraction::operator-(const Fraction& x, const Fraction& y) // subtracting
{
    Fraction temp1;
    Fraction temp2;
    if(x.getden() == y.getden())
    {
        temp1.set(x.getnum() - y.getnum(), x.getden() );
    }
    else
    {
        temp1.set(x.getnum() * y.getden(), x.getden() * y.getden());
        temp2.set(y.getnum() * x.getden(), y.getden() * x.getden());
        temp1.set(temp1.getnum() - temp2.getnum(), temp1.getden());
    }
    reduceFrac(temp1);
    return temp1;

}

友元函数不是类的实例成员。 它们是静态的,并且是其他类的成员,或者没有类。

与他们成为朋友并不会“消除隐含的第一项”,无论这意味着什么。 使它们成为实例成员会删除显式的第一项(通过使其隐式: this ),这是您的实际问题:它们是成员并且它们具有显式的第一项。 要么使它们静态,要么删除friend和第一项。

让成员成为自己班级的朋友是多余的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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