C++ & Java - 重载运算符

C++ & Java - overloading operator

本文关键字:重载 运算符 Java C++      更新时间:2023-10-16

我很难理解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; 
};

并且我想要重载运算符CCD_ 1以打印Fraction。我是怎么做的?我需要在类分数内还是在类分数外过载?

在java中,是否可以重载运算符?如何在那里执行(例如,我想重载运算符+)。

如果这个题目有度量衡的话,那就太好了。

在java中,是否可以重载运算符?

不,Java没有运算符重载。

对于C++:重载<lt;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;
}

所以,作为"我需要在类分数内或类分数外重载它?"的答案您将函数声明为类的friend,以便std::osteam对象可以访问其私有数据。但是,函数是在类之外定义的。

为了给你一个由我自己提供的完整答案,Marcelo和David Rodríguez-dribeas在评论中说道:

在Java中,不能重载运算符

完成我的答案:

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

 nbsp nbsp nbsp nbsp@Marcelo

关于C++重载运算符:

对于C++方面,看看这个问题:stackoverflow.com/questions/4421706/运算符重载

 nbsp nbsp nbsp nbsp@David Rodríguez-dribeas

在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; 
};