C++和Java-运算符重载

3
我很难理解在C++和Java中重载运算符的主题。
例如,我定义了一个新类Fraction:
class Fraction { 
public: 
    Fraction (int top, int bottom) { t = top; b = bottom; } 
    int numerator() { return t; } 
    int denominator() { return b; } 
private: 
    int t, b; 
};

我想重载操作符<<以打印分数。这应该在类Fraction内部还是外部进行重载?
在Java中,是否可以重载运算符?如果可以的话,如何实现(例如,我想重载运算符+)?
如果有关于这个主题的资料,那就太好了。

8
在Java中,你不能重载运算符。这里有一个如何重载 << 的示例:http://www.codeproject.com/KB/cpp/cfraction.aspx - Andrei Sfat
1
在Java中,您无法重载运算符,但默认情况下,+和+=运算符被重载以进行字符串连接。这是唯一的例外。 - Marcelo
对于 C++ 方面,请参考这个问题:https://dev59.com/62855IYBdhLWcg3wUCWC - David Rodríguez - dribeas
4个回答

5

在Java中,能否重载运算符?

不行,Java不支持运算符重载。


2

对于C++:在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;
}

作为对“我需要在Fraction类内或类外进行重载”的回答,您可以将函数声明为该类的友元,以便std :: osteam对象可以访问其私有数据。但是,该函数的定义应该放在类外部。

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
为了给您一个完整的答案,我、Marcelo和David Rodríguez - dribeas在评论中提供了以下内容:
在Java中,您无法重载运算符
为了完善我的回答:
[...],但+和+=运算符默认情况下被重载为字符串连接。这是唯一的例外。
@Marcelo
关于C++重载运算符:
对于C++方面,请看这个问题:stackoverflow.com/questions/4421706/operator-overloading @David Rodríguez - dribeas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接