UML and Operator Overloading

Hi

Can anyone translate this:

+operator+(add:tome &):tome
+friend operator<<(output:ostream &,t:const tome &):ostream &
+operator=(oldTome:const tome &):void

I've done 2 of them but I don't think they are correct:

tome operator + (tome add &);
void tome operator = (const oldtome &);

Thanks
I guess it's:

1
2
3
tome operator+(tome& add);  // The UML says tome&, but it should probably be const tome&
friend ostream& operator<<(ostream& output, const tome& t);
void operator=(const tome& oldTome);

Last edited on
Ok that makes sense. What is the actual use of overloading operators ? I can't see the point in it.
It's so you can say something like:

 
a = b + c;

instead of

 
a = sum(b, c);

I guess that kind of makes sense. Thanks tpb
^^^ that seems trivial, unless you write a large equation that way. Take the basic poly/poly derivative formula, and replace every operator with a function call for a modest example. Its really, really, really nice to be able to write math that looks mostly like math. You still can't use some of the exotic stuff, like sum/product notation, but its a good start.
Here is a slightly less trivial example (though totally trivial compared to a fully worked out class).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class Int {
    int n;
public:
    Int(int n=0) : n(n) {}

    Int operator+(const Int& i) const { return n + i.n; }
    Int operator*(const Int& i) const { return n * i.n; }
    friend std::ostream& operator<<(std::ostream& os, const Int& i) {
        return os << i.n;
    }

    Int add(const Int& i) const { return n + i.n; }
    Int mult(const Int& i) const { return n * i.n; }
    std::ostream& print(std::ostream& os) const { return os << n; }
};

int main() {
    Int a(3), b(5), c(2);

    // with operator overloading
    std::cout << (a + b) * c << '\n';

    // without operator overloading
    c.mult(a.add(b)).print(std::cout) << '\n';
}

Last edited on
Is operator overloading only used in classes ?

I now follow what you guys are saying.
Is operator overloading only used in classes ?

Basically, yes. You can't redefine the meaning of * for regular ints, if that's what you're asking. It needs to be used with user-defined types (like a class or enum).

However, it can be overused. You should only use it in very obvious ways, usually with mathematical entities. Also, you are stuck with the built-in precedence rules, which is somewhat of a problem with <<. E.g., std::cout << a & b << '\n' looks okay, but since << has higher precedence than & it's meaning is (std::cout << a) & (b << '\n'), which doesn't make sense. It needs to be written with parens std::cout << (a & b) << '\n'
Last edited on
Int operator+(const Int& i) const
Ok cool, I follow now. Thanks
Topic archived. No new replies allowed.