Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Advanced C 1992

.pdf
Скачиваний:
93
Добавлен:
17.08.2013
Размер:
4.28 Mб
Скачать

Part V •Appendixes

Only two lines in HELLOCPP.CPP are different from a standard C program. The first line differs because the include file, iostream.h, is a new concept to C programmers. The header file iostream.h accesses C++’s standard I/O functions. These functions are similar to C’s printf() and scanf(), and the header file is much like stdio.h, which most C programs include.

The line that prints the message to the screen is the other difference:

cout << “Hello world, this is C++\n”;

This line may seem strange to the C programmer. It doesn’t appear to take the form of a function call, yet it gets the message to the screen, as if by magic! To the C programmer, using the right shift operator seems to be wrong as well.

C++ has slightly different I/O facilities. Known as streams (the same as in C), these facilities have descriptive names, as shown in Table C.1.

Table C.1. C++ Standard streams.

stream

Description

cout

Output to the standard screen or

 

console, as in C’s stdout.

cin

Input from the standard keyboard

 

or console, as in C’s stdin.

cerr

Output to the error screen or

 

console, as in C’s stderr.

 

Characters sent to the error

 

screen cannot be redirected using

 

I/O redirection.

 

 

Also in the preceding example line, you use the << operator differently from how it is defined in C, because with C++ you can redefine an operator’s function. This redefinition is contextually significant: the meaning of the << operator when used with the stream functions is different from how it’s used in some other context. With stream functions, the >> and << operators are insertion operators that tell C++ what is being sent to the screen or received from the keyboard.

698

Introduction to C++

C C C

 

CCC

 

C

C

C

In C, the comment delimiter is the characters /* and */. C++ has introduced a new type of comment, in which all characters following // until the end of the line are treated as a comment. This type of comment doesn’t require an ending comment marker.

This can create a problem if you’re not careful how you use blanks in statements that are part of mathematical equations. The following lines of code (i = j+k/l) will be improperly parsed by a C/C++ compiler that allows the // comment:

i = j+k//* divide by l */l;

+l;

The intent of this code is that the comment runs to just before the /* delimiter and the variable l, but what happens is the compiler produces:

i = j + k + l;

because the // characters started a C++ single line comment that continues to the end of the line. This isn’t what the programmer wants, however. Because the code is syntactically correct, no warning or error is generated, and the mistake probably won’t be found for some time—probably several hours after the product has been shipped.

To avoid this sort of problem, always use spaces around all operators, including comment operators, as in:

i = j + k / /* divide by l */ l;

+l;

With the spaces, the above fragment compiles correctly, and the spaces make the source easier to read.

Simply stated, C++ accepts // as a delimiter for a single comment line, but it is easy to create the // comment operator in error if you are not careful. C++ also accepts /* */ for opening and closing comment lines.

699

Part V •Appendixes

Unlike C, C++ is a more strongly typed language. C++ also requires you to fully use function prototypes. Function prototypes allow the compiler to check and ensure that all the types match.

Listing C.2 is a slightly more complex program, EXAMP1.CPP. It shows input, output, and a for() loop. With your understanding of cout and cin, this program is self-explanatory.

Listing C.2. EXAMP1.CPP—A C++ program with both input and output.

#include <iostream.h>

void main()

{

 

 

int

nCount =

0;

int

nStart =

0;

cout << “Enter a starting point:”;

cin >> nStart;

cout << “nCount \nHex Decimal Octal \n”;

for (nCount = nStart; nCount < nStart + 16; nCount++)

{

cout << hex << nCount << ‘\t’

<<dec << nCount << ‘\t’

<<oct << nCount << ‘\n’;

}

}

The output of this program, where the starting point was 0, is shown in Figure C.1.

This program shows more of the C++ stream functions, including the method to change the output from decimal to hexadecimal and octal. With cout you can actually do formatted output, but doing so isn’t a trivial matter.

700

Introduction to C++

C C C

 

CCC

 

C

C

C

Figure C.1. Output from EXAMP1.CPP.

Quick & Dirty: If you can’t figure out how to program something in C++, simply do it in C. Then later, when you understand how to write the application in C++, you can convert it. Reverting to C is acceptable when you are first learning how to program in C++, but first try it in C++ before going back to C.

The rest of this chapter covers some of C++’s main features.

Overloading Functions

When you overload something, you expect it to break. C++, however, enables you to overload functions without much risk of breakage.

701

Part V •Appendixes

What is overloading? Many articles written about overloaded functions assume the reader understands overloading. But many readers don’t because it isn’t an obvious concept. For example, you have a program written in C that has floating-point variables (doubles), short int variables, and long (32-bit) integer variables. You can assume that in various places in your program you need to determine the maximum of each data type. With C, you must write a function for each data type, and when writing the code, be sure you call the correct function. If in error you call the integer function to determine maximums and inadvertently pass double parameters, things won’t work well!

Wouldn’t it be nice to have one generic, maximum function that handles all three types? That simply isn’t possible. The function must know the data type when you write it, not when it is called.

C++ gives you an alternative: you can have three functions, all with the same name, but different parameter types. The C++ compiler looks at the parameters and selects the correct function for the data type.

Listing C.3, EXAMP2.CPP, is a program that uses overloaded functions. It shows a maximum function; however, you could choose any function that might use different parameter types with different calls.

Listing C.3. EXAMP2.CPP—Program showing C++ function overloading.

// Program EXAMP2.CPP, written 27 July 1992 by Peter D. Hipson

//Shows the use of overloaded functions.

#include <iostream.h>

//A double, long, and an int max() function are defined. You can

//also have others, such as char, float, and so on.

double

max(double

a, double b);

int

max(int

a, int

b);

long

max(long

a, long

b);

void main()

{

int

nValue1 = 0;

702

Introduction to C++

int

nValue2 = 0;

long

lValue1 = 0;

long

lValue2 = 0;

double

dValue1

= 0.0;

double

dValue2

= 0.0;

cout << “Enter two integer values: “;

cin >> nValue1 >> nValue2;

cout << “The max of “ << nValue1 << “ and “ << nValue2 << “ is “ << max(nValue1, nValue2) << “\n”;

cout << “Enter two long integer values: “;

cin >> lValue1 >> lValue2;

cout << “The max of “ << lValue1 << “ and “ << lValue2 << “ is “ << max(lValue1, lValue2) << “\n”;

cout << “Enter two floating point values: “;

cin >> dValue1 >> dValue2;

cout << “The max of “ << dValue1 << “ and “ << dValue2 << “ is “ << max(dValue1, dValue2) << “\n”;

}

double max( double a, double b)

{

if (a < b)

{

return (b);

}

else

{

return(a);

}

}

C C C

CCC

C C C

continues

703

Part V •Appendixes

Listing C.3. continued

int

max(

int

a,

int

b)

{

 

if (a < b)

{

 

 

return (b);

}

 

else

 

{

 

 

return(a);

}

 

}

 

long

max(

long

a,

long

b)

{

 

if (a < b)

{

return (b);

}

else

{

return(a);

}

}

This program enables you to call max() without considering whether you need to call the floating-point, integer, or long version of the function.

Declaring Variables When Needed

With C, you can declare a variable only at the beginning of a block. Your programs often end up declaring variables far from where they are used, making correlation between a variable and its usage difficult.

704

Introduction to C++

C C C

 

CCC

 

C

C

C

One C++ feature enables you to declare a variable wherever it is needed. In the program EXAMP3.CPP (in Listing C.4), an index that will be used in a for() loop is declared in the for() statement.

Listing C.4. EXAMP3.CPP—Program showing variable declaration in a statement.

//Program EXAMP3.CPP, written 27 July 1992 by Peter D. Hipson

//Shows the use of variable declarations when needed.

#include <iostream.h>

void main()

{

int

nStart = 0;

cout << “Enter a starting point:”;

cin >> nStart;

cout << “nCount \nHex Decimal Octal \n”;

//Here, you declare an integer, nCount, which is used as the

//for() statement’s loop counter. The variable is actually

//declared in the for() loop statement.

for (int nCount = nStart; nCount < nStart + 16; nCount++)

{

cout << hex << nCount << ‘\t’

<<dec << nCount << ‘\t’

<<oct << nCount << ‘\n’;

}

}

705

Part V •Appendixes

In the program, the nCount variable is actually declared in the for() statement, where it is first used:

for (int nCount = nStart; nCount < nStart + 16; nCount++)

This sequence makes it easier to construct loops and other blocks without placing the block’s variables in the program where they are obviously not used.

Default Function Argument Values

When writing functions, you may often create a function that requires many of its parameters for some purposes, yet other calls need only the first few parameters.

You also sometimes need functions that seem to have a variable number of arguments, and you don’t want to code a parameter describing the number of arguments.

Finally, some functions often use default values for some parameters. It is then up to the programmer to code these default values for each call of the function. Heaven forbid should one of the defaults change: you’ll be changing each of the call by hand— a long and tedious process.

C++ provides a solution: specify default values for parameters. This process is simple, being done in the function’s prototype. Listing C.5 is the EXAMP4.CPP program, which demonstrates how to implement default arguments to a function.

Listing C.5. EXAMP4.CPP—Program showing default values for arguments.

//Program EXAMP4.CPP, written 27 July 1992 by Peter D. Hipson

//Shows the use of default values for functions arguments.

#include <limits.h> #include <float.h> #include <iostream.h>

//Defined are a double, long, and an int max() function. You can

//also have others, such as char, float, and so on.

//

//In this version, you have four parameters and find the max of

//the four. Because the minimum number of arguments is two, the final

706

Introduction to C++

//two arguments must default to a value that doesn’t cause

//error values.

double

max(double

a, double b, double c =

DBL_MIN,

double d =

 

DBL_MIN);

 

 

 

 

 

int

max(int

a, int

b, int

c =

INT_MIN,

int

d =

 

INT_MIN);

 

 

 

 

 

long

max(long

a, long

b, long

c = LONG_MIN,

long

d =

 

LONG_MIN);

 

 

 

 

 

void main()

{

 

int

nValue1 = 0;

int

nValue2 = 0;

int

nValue3 = 0;

long

lValue1 = 0;

long

lValue2 = 0;

long

lValue3 = 0;

long

lValue4 = 0;

double

dValue1 = 0.0;

double

dValue2 = 0.0;

cout << “Enter three integer values: “;

cin >> nValue1 >> nValue2 >> nValue3;

cout << “The max of “ << nValue1 <<

and “ << nValue2 <<

and “ << nValue3 <<

is “ << max(nValue1, nValue2, nValue3) << “\n”;

cout << “Enter four long integer values: “;

cin >> lValue1 >> lValue2 >> lValue3 >> lValue4;

cout << “The max of “ << lValue1 <<

and “ << lValue2 <<

and “ << lValue3 <<

and “ << lValue4 <<

C C C

CCC

C C C

continues

707