One of the things
that C++ offers that Java does not is overloaded operators, these provide a
mechanism for writing code that reads much more naturally than code that uses
functions instead. The normal types are the int types (short, char, long, etc),
and float types (float, double) in addition to pointers to one of these. Say
you want to represent values that represent fractions, you can’t use integers
and floats (and doubles) are inexact. In decimal 1/3 can not be represented
(0.3333…..) and in binary there is a problem representing 0.1, which is common
number in everyday use.
If we used a
rational class similar to Java, we might have rational a = new Rational(1, 10);
rational b = new Rational(2, 5); rational c = a.add(b); instead of rational c =
a + b; Although the Java works it is less readable, and we could do a.add(2)
instead of a + 2 but that does not work if we want 2 + b since we can’t write
2.add(b). With addition it too much of a problem to switch them around, but 2 –
a is not the same as a – 2. With rational we can even avoid writing methods
that operate on a rational and an integer value because we can use the fact an
implicit constructor is called to convert the integer value into a rational
value.
The other advantage
of operator overloading, is that we can offer implicit casts to float, so you
could write sin(a) without having to provide your own implementation of sin, we
just need to offer an implicit conversion to double. You should also override
the << and >> for ostream and istream so that you can display a
value using cout << a and read it by using cin >> a. You should
also provide for comparisons to make them behave as expected. You write methods
using operator+, operator- etc rather than using __lt__ as you would do in
Python.
Overloaded
operators allow you to extend the language, but use responsibly. A string class
that uses + to add strings together makes sense, but what would – do? If you
made – remove the string if it appeared at the end, that might be OK for your
use case but “Hello World” - “ ” to give “HelloWorld” could also be argued to
be correct, so it would need documenting. Python allows you to use “-” * 40 to
give a string 40 characters long, so you might consider that as a reasonable
overload.
If you are looking
for help with a C++ project we can help, and can use features
such as operator overload, templates, or just stick to the basics if that is
the level you have been taught to use. We operate 24/7 but the fastest response
time is during the hours 8AM-11PM (PST).
0 comments:
Post a Comment