开发者

C++ & Java - overloading operator

I have a difficult to understand the subject of overloading operator in C++ and Java.

For example, I define a new class 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; 
};

and I want to overload the operator << for printing Fraction. How I do it? I need to overload it inside Class Fraction or outside Class Fraction?

In java - Is it possible to overload operator? How I can do it there (for example, I want to o开发者_运维问答verload the operator +).

If there is a metrial about this subject, It will be great.


In java - Is it possible to overload operator?

No, Java has no operator overloading.


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

So as answer to "I need to overload it inside Class Fraction or outside Class Fraction?" You declare the function as a friend of the class so that the std::osteam object can access its private data. The function, however, is defined outside of the class.


To give you a complete answer provided by myself, Marcelo and David Rodríguez - dribeas in the comments:

in Java you can't overload operators

to complete my answer:

[...], but the + and += operators are overloaded by default for String concatenation. That's the only exception.

        @Marcelo

And about the C++ overloading operators:

For the C++ side of it, look at this question: stackoverflow.com/questions/4421706/operator-overloading

        @David Rodríguez - dribeas


In c++ you can overload an operator for the class that it is applied to. In your case, you'd have

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜