+ - *
+ - * / % ˆ & | << >>
+= -= *= /= %= ˆ= &= |= <<= >>=
~ !
=
== != < > <= >=
&& ||
++ --
, ->* -> () []
new new[] delete delete[]
""
suffix
Yes, =
is an operator, just like +
is. Sure, =
usually
alters its left operand, whereas +
doesn’t, but C++ doesn’t care
about that.
You cannot:
**
, >>>
, or ≠
)
"zulu"+3
do concatenation)
operator+(const Fraction &, double)
,
that doesn’t let you do this:
Fraction a, b; a = 1.2 + b;
operator+
does not create operator+=
,
or operator++
.
If you have a class that represents a number, e.g., class Fraction
,
you should define these methods:
Fraction operator+(const Fraction &)
Fraction &operator+=(const Fraction &)
Fraction &operator++() // preincrement
Fraction operator++(int) // postincrement
The smart programmer will have operator+=
do the real work,
have operator+
and preincrement call it, and have postincrement
call preincrement.
For that matter, define operator-=
in terms of operator+=
(if negation is cheap for your class). Then, as before, you can have
operator-
and predecrement call operator-=
,
and have postdecrement call predecrement.
When possible, implement operator overloading as methods (as part of the
class). When the method is called, the left operand is *this
, and
the right operand is the argument.
Fraction a, b; a += b;
That will call c.operator+=(b)
.
Fraction a, b, c a = b - c;
That will call a.operator=(b.operator-(c))
.
Sometimes, you can’t use a method:
Fraction a, b; a = 1.2 + b;
If operator+
were a method, it would have to be a method of
double
. That wouldn’t work, so it must be a non-member function,
a free function:
Fraction operator+(double, const Fraction &);
Of course, you still need the method that handles Fraction+double
.
Function overloading is your friend.
Java doesn’t allow operator overloading, supposedly because it’s too confusing. There is something to be said for that.
Resist the urge to redefine every 💣⸸꩜※🕱 operator possible. Only define those that:
+=
)
+
file could
concatenate the contents of two files).
A misguided programmer might define a-b
, where a
and b
are strings, to mean “return a
, except remove all the
characters that are also in b
”.
string operator-(string a, const string &b) { size_t pos; while ((pos = a.find_first_of(b)) != string::npos) a.erase(pos, 1); return a; } int main() { const string name = "Jane Fonda"; cout << name-"aeiou" << '\n'; }
Jn Fnd
Dubious. Call it remove_chars()
, instead.