2011-06-18 103 views
3

我很难理解C++和Java中重载运算符的主题。C++&Java - 重载运算符

例如,我定义了一个新的类分数:

class Fraction { 
public: 
    Fraction (int top, int bottom) { t = top; b = bottom; } 
    int numerator() { return t; } 
    int denominator() { return b; } 
private: 
    int t, b; 
}; 

,我想重载运营商<<打印分数。我怎么做?我需要在Class Fraction或Class Fraction之外重载它吗?

在java中 - 是否有可能重载操作符?我该如何做到这一点(例如,我想超载运营商+)。

如果有关于这个问题的metrial,它会很好。

+8

在Java中,你不能超载运营 下面是一个例子如何重载''<<:HTTP://www.codeproject。 com/KB/cpp/cfraction.aspx – sfat

+1

您不能在Java中重载运算符,但是对于字符串连接,默认情况下会重载+和+ =运算符。这是唯一的例外。 – Marcelo

+0

对于它的C++方面,看看这个问题:http://stackoverflow.com/questions/4421706/operator-overloading –

回答

2

对于C++:Overloading the << Operator on msdn

// overload_date.cpp 
// compile with: /EHsc 
#include <iostream> 
using namespace std; 

class Date 
{ 
    int mo, da, yr; 
public: 
    Date(int m, int d, int y) 
    { 
     mo = m; da = d; yr = y; 
    } 
    friend ostream& operator<<(ostream& os, const Date& dt); 
}; 

ostream& operator<<(ostream& os, const Date& dt) 
{ 
    os << dt.mo << '/' << dt.da << '/' << dt.yr; 
    return os; 
} 

int main() 
{ 
    Date dt(5, 6, 92); 
    cout << dt; 
} 

所以为答案 “?我需要重载IT类的分数或课外分数内部” 您声明函数为该类的friend,以便std::osteam对象可以访问其私有数据。但是,该功能是在班级之外定义的。

5

在java中 - 是否有可能超载运算符?

不,Java没有运算符重载。

1

在C++中,您可以为它应用于的类重载一个运算符。在你的情况,你必须

class Fraction { 
public: 
    Fraction (int top, int bottom) { t = top; b = bottom; } 
    int numerator() { return t; } 
    int denominator() { return b; } 
    inline bool operator << (const Fraction &f) const 
    { 
     // do your stuff here 
    } 

private: 
    int t, b; 
}; 
1

给你由我提供了一个完整的答案,马塞洛和大卫·罗德里格斯 - 在评论dribeas:

在Java中,你不能超载运营商

完成我的回答:

[...], 但是+和+ =运算符 默认重载为字符串 级联。这是唯一的 例外。

                @Marcelo

约在C++运算符重载:

对于它的C++的一面,看这个问题:stackoverflow.com/questions/4421706/operator-overloading

                @大卫·罗德里格斯 - dribeas