Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ Timesaving Techniques (2005) [eng].pdf
Скачиваний:
65
Добавлен:
16.08.2013
Размер:
8.35 Mб
Скачать

68 Technique 12: Creating Your Own Types

LISTING 12-4 (continued)

Matrix operator*(double scalar, Matrix& m1 )

{

return scalar_multiplication( m1, scalar );

}

Note that this code replaces the existing operator* that we implemented earlier. Remove the existing implementation or you will get a duplicate definition error from the compiler for having two of the same methods defined.

This code allows us to write either:

Matrix m2 = 4 * m1;

Or

Matrix m2 = m1 * 4;

Because the compiler can resolve either order into a valid method, it will allow you to do both in your code. Because the actual multiplication action is the same in either case, we factor out the code that does the “real” work and call it from both methods. This refactoring reduces the total amount of code, and makes it easier to track down problems.

2. Save the source-code file.

Testing the Matrix Class

After you create a Matrix class, you should create a test driver that not only ensures that your code is correct, but also shows people how to use your code.

Here’s the procedure that creates a test driver that validates various kinds of input from the user, and illustrates how the Matrix class is intended to be used:

1. In the code editor of your choice, open the existing file to hold the code for your test program.

In this example, I named the test program ch12.cpp.

2. Type the code from Listing 12-5 into your file.

Better yet, copy the code from the source file on this book’s companion Web site.

LISTING 12-5: THE MATRIX TEST DRIVER

int main()

{

Matrix

m1(5,5);

Matrix

m2(5,5);

m1[2][2] = 3;

 

1

m2[2][2] =

4;

 

m2[3][3] =

5;

 

 

Matrix m3

=

m1

+ m2;

2

printf(“Matrix 1:\n”);

 

 

m1.Print();

 

 

 

 

printf(“Matrix 3:\n”);

 

 

m3.Print();

 

 

 

 

Matrix m4

=

m3

* 5;

 

3

Matrix m5

=

4 * m4;

 

printf(“Matrix 4:\n”); m4.Print(); printf(“Matrix 5:\n”); m5.Print();

}

3. Compile and run the application in the operating system of your choice.

If you have done everything right, you should see the output from Listing 12-6 in the shell window on your system.

Testing the Matrix Class

69

LISTING 12-6: OUTPUT FROM THE MATRIX TEST PROGRAM

$ ./a.exe

 

 

 

Matrix 1:

 

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

3.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

Matrix 3:

 

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

7.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

5.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

Matrix 4:

 

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

0.000000

0.000000

35.000000

0.000000

0.000000

 

 

0.000000

0.000000

0.000000

25.000000

0.000000

 

 

0.000000

0.000000

0.000000

0.000000

0.000000

 

 

Matrix 5:

0.000000 0.000000 0.000000 0.000000

0.000000

0.000000 0.000000 0.000000 0.000000

0.000000

0.000000 0.000000 140.000000 0.000000

0.000000

0.000000 0.000000 0.000000 100.000000

0.000000

0.000000 0.000000 0.000000 0.000000

0.000000

As you can see from the above output, we are displaying the individual matrix objects that are created in the test program. The output shows that the first matrix (m1) displays the data values which we

placed into it in the line marked

1 in the test

driver code. The line marked

 

shows the addi-

 

 

2

 

 

we then display as

tion of two matrices, which

 

 

 

 

Matrix 3. Likewise, the code marked with

 

3 indi-

 

 

scalar value,

cates the multiplication of a matrix by a

 

 

which is displayed in the output as Matrix 4. If you do the math, you will see that all of the output is correct, indicating that our Matrix class and its manipulation methods are working properly.

As you can see, the matrices display properly and the math is done correctly. We know our test program is correct, and we can use it in the future when we change things.

13 Using Enumerations

Technique

Save Time By

Defining enumerations

Implementing the

Enumeration class

Testing the Enumeration class

An enumeration is a language type introduced with the C language, which has migrated almost untouched into the C++ language. Enumerations are not true types, as classes are. You can’t define

operators for enumerations, nor can you change the way in which they behave. As with pre-processor commands, the enumeration command is really more of a syntactical sugar thing, replacing constant values with more readable names. It allows you slightly better readability, but does nothing to change the way your code works. Enumerations allow you to use meaningful names for values, and allow the compiler to do better type checking. The downside of an enumeration is that because it is simply a syntactical replacement for a data value, you can easily fool the compiler by casting invalid values to the enumerated type.

The basic form of an enumeration looks like this:

enum <name> { value1[=number], value2,

value3,

. . .

valuen

} EnumerationTypeName;

where the <name> field is the enumeration type we are creating, the value parameters are the individual values defined in the enumeration, and number is an optional starting point to begin numbering the enumerated values. For example, take a look at this enumeration:

enum color { Red = 1. White = 2. Blue

} ColorType;

In this example, every time the compiler encounters ColorType::Red in our application, it understands the value to be 1, White would be 2, and Blue 3 (because the numbers are consecutive unless you specify otherwise).

Implementing the Enumeration Class

71

If enumerations actually do not change the logic of your code, why would you bother with them? The primary reason for enumerations is to improve the readability of your code. To illustrate this, here I show you a simple technique involving enumerations you can use to make your code a little safer to use, and a lot easier to understand.

Enumerations are a great way to have the compiler enforce your valid values on the programmer. Rather than checking after the fact to see whether the value is valid, you can let the compiler check at compile-time to validate that the input will be within the range you want. When you specify that a variable is of an enumerated type, the compiler ensures that the value is of that type, insisting that it be one of the values in the enumeration list.

Implementing the Enumeration

Class

An enumeration is normally used when the real-world object it is modeling has very simple, very discrete values. The first example that immediately leaps to mind is a traffic light, which has three possible states: red, yellow, and green. In the following steps, let’s create a simple example using the traffic light metaphor to illustrate how enumerations work and can be used in your application.

1. In the code editor of your choice, create a new file to hold the code for the implementation of the source file.

In this example, the file is named ch13.cpp,

You might notice that enumerations are a simpler form of the Range validation class we developed in Technique 11. Enumerations are enforced by the compiler, not by your code, and require considerably less effort to implement than a Range checking class. At the same time, they are not as robust. Your mileage may vary, but enumerations are usually used more for readability and maintenance concerns than for validation.

although you can use whatever you choose.

2. Type the code from Listing 13-1 into your file.

Better yet, copy the code you find on this book’s companion Web site and change the names of the constants and variables as you choose.

3. Save the source-code file.

LISTING 13-1: THE ENUMERATION PROGRAM

#include <stdio.h>

typedef enum

{

Red = 0,

Yellow,

Green

} TrafficLightColor;

int ChangeLight( int color )

{

switch ( color )

{

case 1: // Red

printf(“Changing light to RED. Stop!!\n”); break;

case 2: // Yellow

printf(“Changing light to YELLOW. Slow down\n”); break;

case 3: // Green

(continued)