C ++ and Java - overload operator

I find it difficult to understand the topic of operator overloading in C ++ and Java.

For example, I define a new Fraction class:

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 <<to print Fraction. How am i doing this? Do I need to overload it inside a class fraction or outside a class fraction?

In java - is it possible to overload a statement? How can I do this (for example, I want to overload the statement +).

If there is a metric in this question, it will be great.

+3
source share
4 answers

For C ++: Overloading <<Statement in 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 . , , .

+2

java - ?

, Java .

+5

++ , .

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

:

[...] + + = String . .

        @Marcelo

And about C ++ overload operators:

For the C ++ side, look at this question: fooobar.com/questions/548 / ...

        @David Rodríguez - dribeas

+1
source

All Articles