Arithmetic Operators. Sams Publishing Object-Oriented Programming in C++
Advertentie
Advertentie
03 3087 CH02 11/29/01 2:19 PM Page 60
60
Chapter 2 casts intVar to type double
. It generates a temporary variable of type double with the same value as intVar
. It is this temporary variable that is multiplied by 10. Since it is type double
, the result fits. This result is then divided by 10 and assigned to the normal int variable intVar
.
Here’s the program’s output: intVar = 211509811 intVar = 1500000000
The first answer, without the cast, is wrong; but in the second answer, the cast produces the correct result.
Before Standard C++, casts were handled using quite a different format. Instead of aCharVar = static_cast<char>(anIntVar); you could say aCharVar = (char)anIntVar; or alternatively aCharVar = char(anIntVar);
One problem with these approaches is that they are hard to see; the syntax blends into the rest of the listing. They are also hard to search for using a Find operation with your source code editor. The new format solves this problem: static_cast is easy to see and easy to search for.
These old casts still work, but their use is discouraged (or deprecated, to use the technical term).
Casts should be used only when absolutely necessary. They are a controlled way of evading
type safety (which means making sure that variables don’t change types by mistake) and can lead to trouble because they make it impossible for the compiler to spot potential problems.
However, sometimes casts can’t be avoided. We’ll see some examples of situations where casts are necessary as we go along.
Arithmetic Operators
As you have probably gathered by this time, C++ uses the four normal arithmetic operators
+
,
-
,
*
, and
/ for addition, subtraction, multiplication, and division. These operators work on all the data types, both integer and floating-point. They are used in much the same way that they are used in other languages, and are closely analogous to their use in algebra. However, there are some other arithmetic operators whose use is not so obvious.
Downloaden
Advertentie