在C ++中扩展运算符重载

时间:2012-11-28 23:11:42

标签: c++ integer overloading operator-keyword

我在C ++方面相当新(我在C中度过了一生,所以我认为是时候花一些时间学习一门新语言以丰富我的知识:))。我有一个名为“Rational”的类,我有getter,setter,constructors等所有特定的函数(这里没有关系)。有趣的是当我尝试重载+, - ,,/运算符时。我能够在两个Rational对象之间成功地做到这一点,例如Rational a(1,5),b(5,5),c; c = a + b;所以这一切都很好。现在我试图通过在Rational和整数之间尝试+, - ,,/来升级我的类,例如2 + a,10-b等。这是我的代码重载的一个片段在Rationals之间:

Rational.cc

...
    Rational Rational::operator+(Rational B) {
            int Num;
            int Den;

            Num = p * B.q + q * B.p;
            Den = q * B.q;

            Rational C(Num, Den);
            C.simplifierFraction();
            return C;
    }

    Rational Rational::operator-(Rational B) {
            int Num;
            int Den;        

            Num = p * B.q - q * B.p;
            Den = q * B.q;

            Rational C(Num, Den);
            C.simplifierFraction();
            return C;
    }



    Rational Rational::operator*(Rational B) 
    {
            int Num;
            int Den;

            Num = p * B.p;
            Den = q * B.q;

            Rational C(Num, Den);
            C.simplifierFraction();
            return C;
    }

    Rational Rational::operator/(Rational B) 
    {
            int Num;
            int Den;
            Rational invB = inverse(B);

            Num = p * invB.p;
            Den = q * invB.q;

            Rational C(Num, Den);
            C.simplifierFraction();
            return C;
    }
...

Rational.h

    Rational operator+(Rational B);
    Rational operator-(Rational B);
    Rational operator*(Rational B);
    Rational operator/(Rational B);


private:
    int p;
    int q;
protected:

TestRat.cc

int main() {
...
    const Rational demi(1,2);      
    const Rational tiers(1,3);      
    const Rational quart(1,4);
    r0 = demi + tiers - quart;         
    r1 = 1 + demi;                     
    r2 = 2 - tiers;                    
    r3 = 3 * quart;                    
    r4 = 1 / r0;
...  

因此,当我尝试运行TestRat.cc时,它说:

testrat.cc:31: error: no match for ‘operator+’ in ‘1 + r9’
testrat.cc:52: error: passing ‘const Rational’ as ‘this’ argument of ‘Rational Rational::operator+(Rational)’ discards qualifiers
testrat.cc:53: error: no match for ‘operator+’ in ‘1 + demi’
testrat.cc:54: error: no match for ‘operator-’ in ‘2 - tiers’
testrat.cc:55: error: no match for ‘operator*’ in ‘3 * quart’
testrat.cc:56: error: no match for ‘operator/’ in ‘1 / r0’

为了能够做到这一点,我该怎么做? 谢谢!

1 个答案:

答案 0 :(得分:3)

TL; DR:

您的运营商应声明为:

Rational operator+(const Rational& B) const;
好吧......这些,至少。 operator =应该返回对*this的引用,但这超出了这些问题的范围。此外,这些运算符被定义为处理Rational个对象,而

r1 = 1 + demi; 

尝试对intRational对象进行操作。你必须在课外定义一个合适的操作符:

inline Rational operator+(int, const Rational& r)
{
    //...
}

我建议您开始使用good book学习C ++。从这里拿起东西并没有真正发挥作用。