Operator Overloading¶
Motivation¶
Operators (+, +=, ->) etc. in C
Only available for simple data types (
int
,float
, pointer arithmetic, …)⟶ defined by the language
Problem: we want more …
Arithmetic operators for
class point
?Intelligent pointers which have a different definition of
->
?… unbounded fantasy here …
Operators, Functions, and Methods¶
Why shouldn’t this be possible? Operators, after all, are functions that are implemented by the compiler.
i += 42
. Method “+=
” on object of typeint
, with parameterint
i = j + 42`. *Static* method "``+
”. Two parameters (typeint
), return typeint
p += point(1,2)
. Define as you like!str += "hallo!"
. Someone else did this already …std::string
C++ Standard Library
Example: Operator +=
on the Object (1)¶
Definition |
Usage |
---|---|
class point
{
public:
point& operator+=(const point &addend)
{
_x += addend._x;
_y += addend._y;
return *this;
}
private:
int _x;
int _y;
};
|
point a(1,2), b(2,3);
a += b;
|
Example: Operator +=
on the Object (2)¶
operator+=(const point &addend)
|
|
point& operator+=(...)
|
|
return *this;
|
|
Example: Operator +
not on the Object (1)¶
class point
{
public:
int x() const { return _x; }
int y() const { return _y; }
};
point operator+(const point &l, const point &r)
{
return point(l.x()+r.x(), l.y()+r.y());
}
Example: Operator +
not on the Object (2)¶
operator+(const point &l, const point &r)
|
|
point operator+(...)
|
|
l.x()+r.x() ...
|
|
Example: Function Objects - Functors (1)¶
Function Call Operator “()
”: for example …
Class without comparison operator
class Item
{
public:
Item(int dies, int das)
: _dies(dies), _das(das) {}
int dies() const { return _dies; }
int das() const { return _das; }
private:
int _dies, _das;
};
Example: Function Objects - Functors (2)¶
- Problem: one wants to sort ⟶ comparison operator
needed
bool operator<(const Item &lhs, const Item &rhs)
{
if (lhs.dies() < rhs.dies())
return true;
if (lhs.dies() > rhs.das())
return false;
return lhs.das() < rhs.das();
}
Problem: he’s global
⟶ Ambiguity!
Not everybody agrees
Example: Function Objects - Functors (3)¶
Solution:
Functors that everybody can tailor to their use
Function Call Operator
Definition |
Usage |
---|---|
class LessOp
{
public:
bool operator()(const Item &lhs, const Item &rhs) const
{
// same as operator<(lhs, rhs)
}
};
|
LessOp less;
if (less(item1, item2))
...
|
Container classes
Algorithms