Transcript Document

1
18
C++ as a Better C;
Introducing Object
Technology
 2007 Pearson Education, Inc. All rights reserved.
2
OBJECTIVES
In this chapter you will learn:
 Several C++ enhancements to C.
 The header files of the C++ Standard Library.
 To use inline functions..
 To overload function definitions.
 To create and use function templates that
perform identical operations on many different
types.
 2007 Pearson Education, Inc. All rights reserved.
3
18.1 Introduction
18.2 C++
18.3 A Simple Program: Adding Two Integers
18.4 C++ Standard Library
18.5 Header Files
18.6 Inline Functions
18.7 References and Reference Parameters
18.11 Function Overloading
18.12 Function Templates
 2007 Pearson Education, Inc. All rights reserved.
4
18.1 Introduction
• The C++ section introduces two additional
programming paradigms
– Object-oriented programming
• With classes, encapsulation, objects, operator overloading,
and inheritance
– Generic programming
• With function templates and class templates
• Emphasize “crafting valuable classes” to create
reusable software
 2007 Pearson Education, Inc. All rights reserved.
5
18.2 C++
• C++ improves on many of C’s features and provides
object-oriented-programming (OOP) capabilities
– Increase software productivity, quality and
reusability
• New requirements demand that the language evolve
rather than simply be displaced by a new language.
• C++ was developed by Bjarne Stroustrup at Bell
Laboratories
– Originally called “C with classes”
– The name C++ includes C’s increment operator (++)
• Indicate that C++ is an enhanced version of C
• C++ standardized in the United States through the
American National Standards Institute (ANSI) and
worldwide through the International Standards
Organization (ISO)
 2007 Pearson Education, Inc. All rights reserved.
6
18.3 A Simple Program: Adding Two
Integers
• C++ file names can have one of several extensions
– Such as: .cpp, .cxx or .C (uppercase)
• Commenting
– A // comment is a maximum of one line long
– A /*…*/ C-style comments can be more than one line long
• iostream
– Must be included for any program that outputs data to the
screen or inputs data from the keyboard using C++-style
stream input/output
• C++ requires you to specify the return type, possibly
void, for all functions
– Specifying a parameter list with empty parentheses is
equivalent to specifying a void parameter list in C
 2007 Pearson Education, Inc. All rights reserved.
7
18.3 A Simple Program: Adding Two
Integers (Cont.)
• Declarations can be placed almost anywhere in a C++
program
– They must appear before their corresponding variables are
used in the program
• Input stream object
– std::cin from <iostream>
• Usually connected to keyboard
• Stream extraction operator >>
- Waits for user to input value, press Enter (Return) key
- Stores value in variable to right of operator
• Converts value to variable data type
• Example
- std::cin >> number1;
• Reads an integer typed at the keyboard
• Stores the integer in variable number1
 2007 Pearson Education, Inc. All rights reserved.
8
18.3 A Simple Program: Adding Two
Integers (Cont.)
• Stream manipulator std::endl (see p. 657)
– Outputs a newline
– Flushes the output buffer
• The notation std::cout specifies that we are
using a name (cout ) that belongs to a
“namespace” (std)
 2007 Pearson Education, Inc. All rights reserved.
9
18.3 A Simple Program: Adding Two
Integers (Cont.)
• Concatenating stream insertion operations
– Use multiple stream insertion operators in a single
statement
• Stream insertion operation knows how to output each type of
data
– Also called chaining or cascading
– Example
• std::cout << "Sum is " << number1 + number2
<< std::endl;
- Outputs "Sum is “
- Then, outputs sum of number1 and number2
- Then, outputs newline and flushes output buffer
 2007 Pearson Education, Inc. All rights reserved.
1
// Fig. 18.1: fig18_01.cpp
2
// Addition program that displays the sum of two numbers.
3
4
#include <iostream> // allows program to perform input and output
10
Outline
5 int main()
6 {
7
int number1; // first integer to add
Declare integer variables
8
9
std::cout << "Enter first integer: "; // prompt user for data
10
std::cin >> number1; // read first integer from user into number1
•fig18_01.c
pp
11
12
13
int number2; // second integer to add
int sum; // sum of number1 and number2
14
15
std::cout << "Enter second integer: "; // prompt user for data
16
std::cin >> number2; // read second integer from user into number2
17
sum = number1 + number2; // add the numbers; store result in sum
18
std::cout << "Sum is " << sum << std::endl; // display sum; Stream
end line
manipulator
std::endl outputs a
19
newline, then “flushes outp
20
return 0; // indicate that program ended successfully
buffer”
21 } // end function main
Enter first integer: 45
Enter second integer: 72
Sum is 117
Concatenating, chaining or
cascading stream insertion
operations
 2007 Pearson Education, Inc. All rights reserved.
11
18.4 C++ Standard Library
• C++ programs
– Built from pieces called classes and functions
• C++ Standard Library
– Rich collections of existing classes and functions
• Reusable in new applications
 2007 Pearson Education, Inc. All rights reserved.
12
18.5Header Files
• Header files
– Each standard library has header files
• Contain function prototypes, data type definitions, and
constants
– Files ending with .h are "old-style" headers
• User defined header files
– Create your own header file
• End it with .h
– Use #include "myFile.h" in other files to load
your header
 2007 Pearson Education, Inc. All rights reserved.
13
C++ Standard
Library header
files
Explanation
<iostream>
Contains function prototypes for the C++ standard input and
standard output functions. This header file replaces header file
<iostream.h>. This header is discussed in detail in
Chapter 26, Stream Input/Output.
<iomanip>
Contains function prototypes for stream manipulators that format
streams of data. This header file replaces header file
<iomanip.h>. This header is used in Chapter 26, Stream
Input/Output.
<cmath>
Contains function prototypes for math library functions. This
header file replaces header file <math.h>.
<cstdlib>
Contains function prototypes for conversions of numbers to text,
text to numbers, memory allocation, random numbers and various
other utility functions. This header file replaces header file
<stdlib>.
<ctime>
Contains function prototypes and types for manipulating the time
and date. This header file replaces header file <time.h>.
<vector>,
<list>
<deque>,
<queue>,
<stack>,
<map>,
<set>,
<bitset>
These header files contain classes that implement the C++
Standard Library containers. Containers store data during a
program’s execution.
Fig. 18.2 | C++ Standard Library headerfiles.
(Part 1Education,
of 3.) Inc.
2007 Pearson
All rights reserved.
14
C++ Standard
Library header
files
Explanation
<cctype>
Contains function prototypes for functions that test characters for
certain properties (such as whether the character is a digit or a
punctuation), and function prototypes for functions that can be
used to convert lowercase letters to uppercase letters and vice
versa. This header file replaces header file <ctype.h>.
<cstring>
Contains function prototypes for C-style string-processing
functions. This header file replaces header file <string.h>.
<typeinfo>
Contains classes for runtime type identification (determining data
types at execution time).
<exception>,
<stdexcept>
<memory>
These header files contain classes that are used for exception
handling (discussed in Chapter 27, Exception Handling).
<fstream>
Contains function prototypes for functions that perform input
from files on disk and output to files on disk. This header file
replaces header file <fstream.h>.
<string>
Contains the definition of class string from the C++ Standard
Library.
<sstream>
Contains function prototypes for functions that perform input
from strings in memory and output to strings in memory.
<functional>
Contains classes and functions used by C++ Standard Library
algorithms.
Contains classes and functions used by the C++ Standard Library
to allocate memory to the C++ Standard Library containers. This
header is used in Chapter 27, Exception Handling.
Fig. 18.2 | C++ Standard Library headerfiles.
(Part 2Education,
of 3.) Inc.
2007 Pearson
All rights reserved.
15
C++ Standard
Library header
files
Explanation
<iterator>
Contains classes for accessing data in the C++ Standard Library
containers.
<algorithm>
Contains functions for manipulating data in C++ Standard
Library containers.
<cassert>
Contains macros for adding diagnostics that aid program
debugging. This replaces header file <assert.h> from prestandard C++.
<cfloat>
Contains the floating-point size limits of the system. This header
file replaces header file <float.h>.
<climits>
Contains the integral size limits of the system. This header file
replaces header file <limits.h>.
<cstdio>
Contains function prototypes for the C-style standard
input/output library functions and information used by them. This
header file replaces header file <stdio.h>.
<locale>
Contains classes and functions normally used by stream
processing to process data in the natural form for different
languages (e.g., monetary formats, sorting strings, character
presentation, and so on).
<limits>
Contains classes for defining the numerical data type limits on
each computer platform.
<utility>
Contains classes and functions that are used by many C++
Standard Library header files.
Fig. 18.2 | C++ Standard Library header files. (Part 3 of 3.)
 2007 Pearson Education, Inc. All rights reserved.
16
18.6Inline Functions
• Function calls
– Cause execution-time overhead
– Qualifier inline before function return type "advises" a
function to be inlined
• Puts copy of function's code in place of function call
– Speeds up performance but increases file size
– Compiler can ignore the inline qualifier
• Ignores all but the smallest functions
inline double cube( const double s )
{ return s * s * s; }
• Using statements
– By writing using std::cout; we can write cout instead
of std::cout in the program
– Same applies for std::cin and std::endl
 2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.3: fig18_03.cpp
2 // Using an inline function to calculate the volume of a cube.
17
Outline
3 #include <iostream>
4 using std::cout;
5 using std::cin;
6 using std::endl;
fig18_03.cpp
(1 of 2 )
7
8 // Definition of inline function cube. Definition of function appears
9 // before function is called, so a function prototype is not required.
10 // First line of function definition acts as the prototype.
11 inline double cube( const double side )
12 {
13
return side * side * side; // calculate the cube of side
14 } // end function cube
15
16 int main()
17 {
18
double sideValue; // stores value entered by user
19
 2007 Pearson Education,
Inc. All rights reserved.
20
for ( int i = 1; i <= 3; i++ )
21
{
18
Outline
22
cout << "\nEnter the side length of your cube: ";
23
cin >> sideValue; // read value from user
fig18_03.cpp
24
25
// calculate cube of sideValue and display result
26
cout << "Volume of cube with side "
<< sideValue << " is " << cube( sideValue ) << endl;
27
28
(2 of 2 )
}
29
30
return 0; // indicates successful termination
31 } // end main
Enter the side length of your cube: 1.0
Volume of cube with side 1 is 1
Enter the side length of your cube: 2.3
Volume of cube with side 2.3 is 12.167
Enter the side length of your cube: 5.4
Volume of cube with side 5.4 is 157.464
 2007 Pearson Education,
Inc. All rights reserved.
19
C++ keywords
Keywords common to the C and C++ programming languages
auto
continue
break
default
case
do
char
double
const
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
Fig. 18.4 | C++ keywords. (Part 1 of 2.)
 2007 Pearson Education, Inc. All rights reserved.
20
C++ keywords
C++-only keywords
and
bool
and_eq
catch
delete
asm
class
bitand
compl
bitor
const_cast
dynamic_cast explicit
export
false
friend
inline
mutable
namespace
new
not
not_eq
operator
or
or_eq
private
protected
public
reinterpret_cast static_cast
template
this
throw
true
try
typeid
typename
using
virtual
wchar_t
xor
xor_eq
Fig. 18.4 | C++ keywords. (Part 2 of 2.)
 2007 Pearson Education, Inc. All rights reserved.
21
18.7 References and Reference
Parameters
• Two ways to pass arguments to functions (see p.
664)
– Pass-by-value
• A copy of the argument’s value is passed to the called
function
• Changes to the copy do not affect the original variable’s
value in the caller
- Prevents accidental side effects of functions
– Pass-by-reference
• Gives called function the ability to access and modify
the caller’s argument data directly
 2007 Pearson Education, Inc. All rights reserved.
22
18.7 References and Reference
Parameters (Cont.)
• Reference Parameter
– An alias for its corresponding argument in a function
call
– & placed after the parameter type in the function
prototype and function header
– Example
• int &count in a function header
- Pronounced as “count is a reference to an int”
– Parameter name in the body of the called function
actually refers to the original variable in the calling
function
 2007 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 18.5: fig18_05.cpp
// Comparing pass-by-value and pass-by-reference with references.
3
4
#include <iostream>
using std::cout;
5
6
using std::endl;
7
int squareByValue( int ); // function prototype (value pass)
8
9
void squareByReference( int & ); // function prototype (reference pass)
23
Outline
fig18_05.cpp
(1 of 2 )
10 int main()
11 {
12
13
14
15
int x = 2; // value to square using squareByValue
int z = 4; // value to square using squareByReference
16
cout << "x = " << x << " before squareByValue\n";
17
18
cout << "Value returned by squareByValue: "
<< squareByValue( x ) << endl;
19
20
cout << "x = " << x << " after squareByValue\n" << endl;
21
22
// demonstrate squareByReference
cout << "z = " << z << " before squareByReference" << endl;
23
24
squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;
// demonstrate squareByValue
25
return 0; // indicates successful termination
26 } // end main
 2007 Pearson Education,
Inc. All rights reserved.
27
24
28 // squareByValue multiplies number by itself, stores the
Outline
29 // result in number and returns the new value of number
30 int squareByValue( int number )
fig18_05.cpp
31 {
32
return number *= number; // caller's argument not modified
(2 of 2 )
33 } // end function squareByValue
34
35 // squareByReference multiplies numberRef by itself and stores the result
36 // in the variable to which numberRef refers in the caller
37 void squareByReference( int &numberRef )
38 {
39
numberRef *= numberRef; // caller's argument modified
40 } // end function squareByReference
x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue
z = 4 before squareByReference
z = 16 after squareByReference
 2007 Pearson Education,
Inc. All rights reserved.
25
18.11 Function Overloading
• Overloaded functions (see p. 672)
– Overloaded functions have
• Same name
• Different sets of parameters
– Compiler selects proper function to execute based on
number, types and order of arguments in the function
call
– Commonly used to create several functions of the
same name that perform similar tasks, but on
different data types
 2007 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 18.10: fig18_10.cpp
// Overloaded functions.
3
4
5
#include <iostream>
using std::cout;
using std::endl;
26
Outline
6
7
8
// function square for int values
int square( int x )
9 {
10
fig18_10.cpp
Defining a square function for ints
cout << "square of integer " << x << " is ";
11
return x * x;
12 } // end function square with int argument
13
14 // function square for double values
15 double square( double y )
16 {
17
18
19
20
21
22
23
24
25
26
27
28
Defining a square function for doubles
cout << "square of double " << y << " is ";
return y * y;
} // end function square with double argument
int main()
{
cout << square( 7 ); // calls int version
cout << endl;
cout << square( 7.5 ); // calls double version
cout << endl;
return 0; // indicates successful termination
} // end main
Output confirms that the proper
function was called in each case
square of integer 7 is 49
square of double 7.5 is 56.25
 2007 Pearson Education,
Inc. All rights reserved.
27
18.12 Function Templates
• Function templates
– More compact and convenient form of overloading
• Identical program logic and operations for each data
type
– Function template definition
•
•
•
•
Written by programmer once
Essentially defines a whole family of overloaded functions
Begins with the template keyword
Contains template parameter list of formal type parameters
for the function template enclosed in angle brackets (<>)
• Formal type parameters
- Preceded by keyword typename or keyword class
- Placeholders for fundamental types or user-defined
types
 2007 Pearson Education, Inc. All rights reserved.
28
18.12 Function Templates(Cont.)
• Function-template specializations
– Generated automatically by the compiler to handle each
type of call to the function template
– Example for function template max with type parameter T
called with int arguments
• Compiler detects a max invocation in the program code
• int is substituted for T throughout the template definition
• This produces function-template specialization max< int >
 2007 Pearson Education, Inc. All rights reserved.
1
// Fig. 15.11: fig15_11.cpp
2
// Using a function template
3
#include <iostream>
29
4
5
using std::cout;
6
using std::cin;
7
using std::endl;
8
9
template < class T >
10 T maximum( T value1, T value2, T value3 )
11 {
12
fig15_11.cpp (Part 1 of 2)
T max = value1;
13
14
if ( value2 > max )
15
max = value2;
16
17
if ( value3 > max )
18
max = value3;
19
20
return max;
21 } // end function template maximum
22
 2007 Pearson Education, Inc. All rights reserved.
23 int main()
30
24 {
25
int int1, int2, int3;
26
27
cout << "Input three integer values: ";
28
cin >> int1 >> int2 >> int3;
29
cout << "The maximum integer value is: "
30
<< maximum( int1, int2, int3 );
// int version
31
32
double double1, double2, double3;
33
34
cout << "\nInput three double values: ";
35
cin >> double1 >> double2 >> double3;
36
cout << "The maximum double value is: "
37
fig15_11.cpp (Part 2 of 2)
<< maximum( double1, double2, double3 ); // double version
38
39
char char1, char2, char3;
40
41
cout << "\nInput three characters: ";
42
cin >> char1 >> char2 >> char3;
43
cout << "The maximum character value is: "
44
<< maximum( char1, char2, char3 )
45
<< endl;
// char version
46
47
return 0;
48 } // end function main
 2007 Pearson Education, Inc. All rights reserved.
Input three
The maximum
Input three
The maximum
Input three
The maximum
integer values: 1 2 3
integer value is: 3
double values: 3.3 2.2 1.1
double value is: 3.3
characters: A C B
character value is: C
31
 2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.12: maximum.h
2 // Definition of function template maximum.
32
Outline
3
4 template < class T >
// or template< typename T >
5 T maximum( T value1, T value2, T value3 )
6 {
7
T maximumValue = value1; // assume value1 is maximum
8
9
// determine whether value2 is greater than maximumValue
10
if ( value2 > maximumValue )
11
maximumValue = value2;
12
13
// determine whether value3 is greater than maximumValue
14
if ( value3 > maximumValue )
15
maximumValue = value3;
16
17
return maximumValue;
18 } // end function template maximum
 2007 Pearson Education,
Inc. All rights reserved.
1
2
// Fig. 18.13: fig18_13.cpp
// Function template maximum test program.
3
4
#include <iostream>
using std::cout;
5
using std::cin;
6
using std::endl;
fig18_13.cpp
7
8
#include "maximum.h" // include definition of function template maximum
(1 of 2 )
33
Outline
9
10 int main()
11 {
12
// demonstrate maximum with int values
13
14
15
int int1, int2, int3;
cout << "Input three integer values: ";
16
17
cin >> int1 >> int2 >> int3;
18
19
// invoke int version of maximum
cout << "The maximum integer value is: "
20
21
22
<< maximum( int1, int2, int3 );
// demonstrate maximum with double values
23
24
double double1, double2, double3;
25
26
27
cout << "\n\nInput three double values: ";
cin >> double1 >> double2 >> double3;
 2007 Pearson Education,
Inc. All rights reserved.
28
// invoke double version of maximum
29
cout << "The maximum double value is: "
30
34
Outline
<< maximum( double1, double2, double3 );
31
32
// demonstrate maximum with char values
33
char char1, char2, char3;
fig18_13.cpp
(2 of 2 )
34
35
cout << "\n\nInput three characters: ";
36
cin >> char1 >> char2 >> char3;
37
38
// invoke char version of maximum
39
cout << "The maximum character value is: "
40
<< maximum( char1, char2, char3 ) << endl;
41
return 0; // indicates successful termination
42 } // end main
Input three integer values: 1 2 3
The maximum integer value is: 3
Input three double values: 3.3 2.2 1.1
The maximum double value is: 3.3
Input three characters: A C B
The maximum character value is: C
 2007 Pearson Education,
Inc. All rights reserved.