2011-06-18 102 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