重载运算符输出

时间:2013-04-30 04:46:36

标签: c++ operator-overloading

尽管我对Java基础知识有一些了解,但我对c ++还是比较陌生的。

我有这个运算符<<:

std::ostream& operator<<(std::ostream& out, Rational& r) {
    int a;
    int b;
    int c;
    int d;

    b = r.n_;
    c = r.d_;
    if (c >= b) {
        a = (b / c);
        d = (b % c);

        r.n_ = d;}


    return out << r.n_ << '/' << r.d_;
    }

基本上我要做的是;如果我要输出的分数是不合适的分数,我希望能够在输出之前将其转换为混合数字格式。我已经编写了if语句来计算混合数,但是我很难弄清楚如何使用&lt;&lt;运算符,因为它只能采用两个参数。如果有办法(不编辑类实例变量)。

(Rational类有两个实例变量Numerator和Denominator)

非常感谢任何帮助或想法,提前感谢。 ^^

提前致谢。

1 个答案:

答案 0 :(得分:3)

我真的不明白你的意思,<<运营商只能接受两个参数&#39;。看起来你正试图做这样的事情:

std::ostream& operator<<(std::ostream& out, Rational& r)
{
    if (r.n_ > r.d_)
    {
        int whole = r.n_ / r.d_;
        int numerator = r.n_ % r.d_;
        return out << whole << ' ' << numerator << '/' << r.d_;
    }

    return out << r.n_ << '/' << r.d_;
}

我认为这看起来很简单。也许我对你的问题遗漏了什么?