Tài liệu Thinking in C++ Second Edition - Pdf 91



Thinking
In
C++

Bruce Eckel

President, MindView Inc.Prentice Hall PTR
Upper Saddle River, New Jersey 07458
Publisher:
Alan Apt
Production Editor:
Mona Pompilli

Development Editor:
Sondra Chavez
Book Design, Cover Design and Cover Photo:
Daniel Will-Harris,

Copy Editor:
Shirley Michaels
Production Coordinator:
Lori Bulwin
Editorial Assistant:

Prentice-Hall of India Private Limited,
New Delhi

Prentice-Hall of Japan, Inc.,
Tokyo

Simon & Schuster Asia Pte. Ltd.,
Singapore

Editora Prentice-Hall do Brasil, Ltda.,
Rio de Janeiro

dedication
to the scholar, the healer, and the muse What’s inside...
Thinking in C++ 2
nd
edition VERSION
TICA17 .............................................. 1
Preface 17
Prerequisites...............................17
Thinking in C....................................17
Learning C++.............................18
Goals ..........................................19
Chapters......................................20
Exercises ....................................23
Source code................................24
Coding standards .............................. 25

Maximal leverage with libraries ....... 57
Source-code reuse with templates..... 57
Error handling...................................57
Programming in the large ................. 58
Strategies for transition..............58
Guidelines......................................... 58
Management obstacles...................... 60
Summary....................................61
2: Making & using objects 63
The process of language translation63
Interpreters........................................ 64
Compilers.........................................64
The compilation process...................65
Tools for separate compilation... 66
Declarations vs. definitions...............67
Linking.............................................71
Using libraries ..................................72
Your first C++ program.............. 73
Using the iostreams class.................. 73
Namespaces...................................... 74
Fundamentals of program structure ..75
"Hello, world!".................................76
Running the compiler .......................77
More about iostreams................. 77
Character array concatenation........... 78
Reading input ...................................78
Simple file manipulation...................79
Introducing
string
s ....................80

Introduction to operators..........102
Precedence...................................... 103
Auto increment and decrement....... 103
Introduction to data types.........104
Basic built-in types......................... 104
bool
,
true
, &
false
.......................... 105
Specifiers........................................ 106
Introduction to Pointers .................. 108
Modifying the outside object .......... 112
Introduction to C++ references....... 114
Pointers and references as modifiers115
Scoping.....................................117
Defining variables on the fly ..........118
Specifying storage allocation ...120
Global variables.............................. 120
Local variables ............................... 121
static
............................................... 121
extern
............................................. 123
Constants........................................ 124
volatile
........................................... 125
Operators and their use.............126
Assignment..................................... 126

Debugging hints .......................150
Debugging flags ............................. 151
Turning variables and expressions into
strings.............................................152
The C
assert( )
macro.....................153
Make: an essential tool for separate
compilation ..............................154
Make activities................................155
Makefile
s in this book.................... 157
An example
makefile
.....................158
Summary..................................160
Exercises.................................. 160
4: Data abstraction 163
A tiny C-like library.................164
Dynamic storage allocation ............167
Bad guesses ....................................170
What's wrong?..........................171
The basic object ....................... 172
What's an object? ..................... 178
Abstract data typing................. 179
Object details ...........................179
Header file etiquette.................181
Importance of header files..............181
The multiple-declaration problem...183
The preprocessor directives

Handle classes.......................... 208
Hiding the implementation ............. 208
Reducing recompilation.................. 208
Summary..................................211
Exercises.................................. 211

6: Initialization & cleanup 213
Guaranteed initialization with the
constructor................................214
Guaranteed cleanup with the
destructor..................................215
Elimination of the definition block217
for
loops......................................... 219
Storage allocation........................... 220
Stash
with constructors and
destructors................................221
Stack
with constructors &
destructors................................224
Aggregate initialization............227
Default constructors .................229
Summary..................................230
Exercises ..................................231
7: Function overloading &
default arguments 233
More name decoration..............234
Overloading on return values..........235
Type-safe linkage ........................... 235

const
value................ 259
Passing and returning addresses...... 262
Classes......................................265
const
and
enum
in classes.............. 265
Compile-time constants in classes..268
const
objects & member functions.271
ROMability.....................................275
volatile
.....................................275
Summary..................................277
Exercises.................................. 277
9: Inline functions 281
Preprocessor pitfalls.................281
Macros and access..........................284
Inline functions ........................285
Inlines inside classes.......................285
Access functions............................. 286
Stash & Stack with inlines.......292
Inlines & the compiler..............292
Limitations...................................... 292
Order of evaluation......................... 293
Hidden activities in constructors &
destructors ...................................... 294
Forward referencing.................295
Reducing clutter....................... 295

Argument-passing guidelines..........331
The copy-constructor ............... 331

Passing & returning by value.......... 331
Copy-construction .......................... 336
Default copy-constructor ................341
Alternatives to copy-construction...344
Pointers to members.................345
Functions........................................ 346
Summary..................................349
Exercises ..................................349
12: Operator overloading 351
Warning & reassurance.............351
Syntax.......................................352
Overloadable operators.............353
Unary operators.............................. 353
Binary operators ............................. 358
Arguments & return values............. 369
Unusual operators........................... 371
Operators you can’t overload.......... 375
Nonmember operators..............375
Basic guidelines.............................. 377
Overloading assignment...........378
Behavior of
operator=
................... 379
Automatic type conversion.......389
Constructor conversion................... 389
Operator conversion ....................... 391
A perfect example: strings.............. 393

Exercises ..................................423
14: Inheritance & composition
425
Composition syntax ................. 425
Inheritance syntax.................... 427
The constructor initializer list .. 429
Member object initialization........... 429
Built-in types in the initializer list...429
Combining composition &
inheritance................................ 430
Order of constructor & destructor calls432
Name hiding................................... 434
Functions that don’t automatically
inherit .............................................435
Choosing composition vs.
inheritance................................ 436
Subtyping ....................................... 438
Specialization .................................440
private
inheritance.........................442
protected
.................................443
protected
inheritance ..................... 444
Multiple inheritance................. 445
Incremental development......... 445
Upcasting ................................. 446
Why “upcasting”?........................... 447
Upcasting and the copy-constructor
(not indexed)...................................447

VTABLE
..475

virtual
functions & constructors479
Order of constructor calls ............... 480
Behavior of virtual functions inside
constructors .................................... 481
Destructors and
virtual
destructors482
Virtuals in destructors..................... 483
Summary..................................484
Exercises ..................................484
16: Introduction to templates
487
Containers & iterators ..............487
The need for containers .................. 489
Overview of templates..............490
The C approach ..............................490
The Smalltalk approach.................. 490
The template approach.................... 492
Template syntax........................493
Non-inline function definitions....... 495
The stack as a template................... 496
Constants in templates.................... 498
Stash
and
stack
as templates ..500

18: Iostreams 555
Why iostreams?........................ 555
True wrapping ................................557
Iostreams to the rescue............. 559
Sneak preview of operator overloading560
Inserters and extractors...................561
Common usage............................... 562
Line-oriented input .........................564
File iostreams........................... 566
Open modes.................................... 568
Iostream buffering....................568
Using
get( )
with a streambuf .........570
Seeking in iostreams ................ 570
Creating read/write files .................572
stringstreams ............................573
strstreams .................................573
User-allocated storage .................... 573
Automatic storage allocation ..........576
Output stream formatting.........579
Internal formatting data .................. 580
An exhaustive example................... 584
Formatting manipulators.......... 587
Manipulators with arguments .........589
Creating manipulators..............592
Effectors ......................................... 593
Iostream examples....................595
Code generation..............................595
A simple datalogger........................ 603

Partial Specialization...................... 631
A practical example........................ 631
Design & efficiency........................ 635
Preventing template bloat ............... 635
Explicit instantiation ................636
Explicit specification of template
functions.........................................637
Controlling template instantiation637
The inclusion vs. separation models639
The export keyword........................ 639
Template programming idioms.639
The “curiously-recurring template” 639
Traits .............................................. 639
Summary..................................639
20: STL Containers & Iterators
641
Containers and iterators............641
STL reference documentation......... 643
The Standard Template Library 643
The basic concepts ...................645
Containers of strings.................649
Inheriting from STL containers 651
A plethora of iterators ..............653
Iterators in reversible containers..... 655
Iterator categories...........................656
Predefined iterators......................... 657
Basic sequences: vector, list &
deque........................................663
Basic sequence operations.............. 663
vector........................................666

The magic of maps .........................733
Multimaps and duplicate keys ........738
Multisets.........................................741
Combining STL containers......744
Cleaning up containers of pointers747
Creating your own containers .. 749
Freely-available STL extensions751
Summary..................................753
Exercises.................................. 754
21: STL Algorithms 757
Function objects....................... 757
Classification of function objects.... 759
Automatic creation of function objects759
SGI extensions................................ 773
A catalog of STL algorithms.... 779
Support tools for example creation. 781
Filling & generating........................785
Counting......................................... 787
Manipulating sequences.................. 788
Searching & replacing ....................793
Comparing ranges........................... 799
Removing elements ........................ 802
Sorting and operations on sorted ranges805
Heap operations.............................. 816
Applying an operation to each element
in a range........................................817
Numeric algorithms........................825
General utilities ..............................828
Creating your own STL-style
algorithms ................................830

Better exception specifications? ..... 871
Catching any exception ..................871
Rethrowing an exception ................ 872
Uncaught exceptions....................... 872
Function-level try blocks................874
Cleaning up ..............................874
Constructors .............................878
Making everything an object .......... 879
Exception matching..................882
Standard exceptions..................884
Programming with exceptions..885
When to avoid exceptions............... 885
Typical uses of exceptions.............. 886
Overhead ..................................890
Summary..................................890
Exercises ..................................891
24: Run-time type
identification 893
The “Shape” example...............893
What is RTTI?..........................894
Two syntaxes for RTTI................... 894
Syntax specifics........................898
typeid( )
with built-in types............ 898
Producing the proper type name ..... 899
Nonpolymorphic types ................... 899
Casting to intermediate levels......... 900
void
pointers................................... 902
Using RTTI with templates ............902

Basic complexity hiding ................. 935
Factories: encapsulating object
creation.....................................935
Polymorphic factories.....................938
Abstract factories............................ 941
Virtual constructors ........................ 943
Callbacks..................................949
Functor/Command..........................949
Strategy........................................... 949
Observer.........................................949
Multiple dispatching ................959
Visitor, a type of multiple dispatching962
Efficiency................................. 966
Flyweight........................................ 966
The composite..........................966
Evolving a design: the trash
recycler.....................................966
Improving the design ............... 971
“Make more objects”......................971
A pattern for prototyping creation .. 976
Abstracting usage.....................987
Applying double dispatching... 992
Implementing the double dispatch..992
Applying the visitor pattern ..... 997
RTTI considered harmful? .....1003
Summary................................1006
Exercises................................ 1007

26: Tools & topics 1008
The code extractor..................1008

Include guards on header files1077
Use of namespaces................. 1078
Use of
require( )
and
assure( )
1078
B: Programming guidelines
1079
C: Recommended reading 1089
C............................................. 1089
General C++........................... 1089
My own list of books.................... 1090
Depth & dark corners............. 1090
Analysis & Design................. 1090
The STL................................. 1092
Design Patterns ......................1092
D:Compiler specifics 1093
Index 1101


17
Preface
Like any human language, C++ provides a way to express
concepts. If successful, this medium of expression will be
significantly easier and more flexible than the alternatives as
problems grow larger and more complex.
You can’t just look at C++ as a collection of features; some of the features make no sense in
isolation. You can only use the sum of the parts if you are thinking about
design

will: As a C programmer with a very no-nonsense, nuts-and-bolts attitude about
programming. Worse, my background and experience was in hardware-level embedded
programming, where C has often been considered a high-level language and an inefficient
overkill for pushing bits around. I discovered later that I wasn’t even a very good C
programmer, hiding my ignorance of structures,
malloc( )
&
free( )
,
setjmp( )
&
longjmp( )
,
and other “sophisticated” concepts, scuttling away in shame when the subjects came up in
conversation rather than reaching out for new knowledge.
When I began my struggle to understand C++, the only decent book was Stroustrup’s self-
professed “expert’s guide,
1
” so I was left to simplify the basic concepts on my own. This
resulted in my first C++ book,
2
which was essentially a brain dump of my experience. That
was designed as a reader’s guide, to bring programmers into C and C++ at the same time.
Both editions
3
of the book garnered an enthusiastic response and I still feel it is a valuable
resource.
At about the same time that
Using C++
came out, I began teaching the language. Teaching

C++ Inside & Out
,

ibid.
Preface 19
problem in discrete, easy-to-digest steps and for a hands-on seminar (the ideal learning
situation), there are exercises following each of the short lessons.
This book developed over the course of two

years, and the material in this book has been
road-tested in many forms in many different seminars. The feedback that I’ve gotten from
each seminar has helped me change and refocus the material until I feel it works well as a
teaching medium. But it isn’t just a seminar handout – I tried to pack as much information as I
could within these pages, and structure it to draw you through, onto the next subject. More
than anything, the book is designed to serve the solitary reader, struggling with a new
programming language.
Goals
My goals in this book are to:
1.
Present the material a simple step at a time, so the reader can easily digest
each concept before moving on.
2.
Use examples that are as simple and short as possible. This sometimes
prevents me from tackling “real-world” problems,
but I’ve found that beginners are usually happier when they can understand
every detail of an example rather than being impressed by the scope of the
problem it solves. Also, there’s a severe limit to the amount of code that can
be absorbed in a classroom situation. For this I will no doubt receive
criticism for using “toy examples,” but I’m willing to accept that in favor of
producing something pedagogically useful. Those who want more complex

minds more active and involved during a hands-on seminar, but it gives the
reader a greater sense of accomplishment.
6.
Provide the reader with a solid foundation so they can understand the issues
well enough to move on to more difficult coursework and books.
7.
I’ve endeavored not to use any particular vendor’s version of C++ because,
for learning the language, I don’t feel like the details of a particular
implementation are as important as the language itself. Most vendors’
documentation concerning their own implementation specifics is adequate.
Chapters
C++ is a language where new and different features are built on top of an existing syntax.
(Because of this it is referred to as a
hybrid
object-oriented programming language.) As more
people have passed through the learning curve, we’ve begun to get a feel for the way C
programmers move through the stages of the C++ language features. Because it appears to be
the natural progression of the C-trained mind, I decided to understand and follow this same
path, and accelerate the process by posing and answering the questions that came to me as I
learned the language and that came from audiences as I taught it.
This course was designed with one thing in mind: the way people learn the C++ language.
Audience feedback helped me understand which parts were difficult and needed extra
illumination. In the areas where I got ambitious and included too many features all at once, I
came to know – through the process of presenting the material – that if you include a lot of
new features, you have to explain them all, and the student’s confusion is easily compounded.
As a result, I’ve taken a great deal of trouble to introduce the features as few at a time as
possible; ideally, only one at a time per chapter.
The goal, then, is for each chapter to teach a single feature, or a small group of associated
features, in such a way that no additional features are relied upon. That way you can digest
each piece in the context of your current knowledge before moving on. To accomplish this, I

private
. This means you
can separate the underlying implementation from the interface that the client programmer
sees, and thus allow that implementation to be easily changed without affecting client code.
The keyword
class
is also introduced as a fancier way to describe a new data type, and the
meaning of the word “object” is demystified (it’s a variable on steroids).

(3) Initialization & cleanup.
One of the most common C errors results from uninitialized
variables. The
constructor
in C++ allows you to guarantee that variables of your new data
type (“objects of your class”) will always be properly initialized. If your objects also require
some sort of cleanup, you can guarantee that this cleanup will always happen with the C++
destructor
.

(4) Function overloading & default arguments.
C++ is intended to help you build big,
complex projects. While doing this, you may bring in multiple libraries that use the same
function name, and you may also choose to use the same name with different meanings within
a single library. C++ makes this easy with
function overloading
, which allows you to reuse
the same function name as long as the argument lists are different. Default arguments allow
you to call the same function in different ways by automatically providing default values for
some of your arguments.


how names are controlled using two techniques. First, the
static
keyword is used to control
visibility and linkage, and its special meaning with classes is explored. A far more useful
technique for controlling names at the global scope is C++’s
namespace
feature, which
allows you to break up the global name space into distinct regions.
(9) References & the copy-constructor.
C++ pointers work like C pointers with the
additional benefit of stronger C++ type checking. There’s a new way to handle addresses;
from Algol and Pascal, C++ lifts the
reference
which lets the compiler handle the address
manipulation while you use ordinary notation. You’ll also meet the copy-constructor, which
controls the way objects are passed into and out of functions by value. Finally, the C++
pointer-to-member is illuminated.

(10) Operator overloading.
This feature is sometimes called “syntactic sugar.” It lets you
sweeten the syntax for using your type by allowing operators as well as function calls. In this
chapter you’ll learn that operator overloading is just a different type of function call and how
to write your own, especially the sometimes-confusing uses of arguments, return types, and
making an operator a member or friend.

(11) Dynamic object creation.
How many planes will an air-traffic system have to handle?
How many shapes will a CAD system need? In the general programming problem, you can’t
know the quantity, lifetime or type of the objects needed by your running program. In this
chapter, you’ll learn how C++’s

providing the compiler with a way to substitute type names in the body of a class or function.
This supports the use of
container class
libraries, which are important tools for the rapid,
robust development of object-oriented programs. This extensive chapter gives you a thorough
grounding in this essential subject.

(15) Multiple inheritance.
This sounds simple at first: A new class is inherited from more
than one existing class. However, you can end up with ambiguities and multiple copies of
base-class objects. That problem is solved with virtual base classes, but the bigger issue
remains: When do you use it? Multiple inheritance is only essential when you need to
manipulate an object through more than one common base class. This chapter explains the
syntax for multiple inheritance, and shows alternative approaches – in particular, how
templates solve one common problem. The use of multiple inheritance to repair a “damaged”
class interface is demonstrated as a genuinely valuable use of this feature.

(16) Exception handling.
Error handling has always been a problem in programming. Even if
you dutifully return error information or set a flag, the function caller may simply ignore it.
Exception handling is a primary feature in C++ that solves this problem by allowing you to
“throw” an object out of your function when a critical error happens. You throw different
types of objects for different errors, and the function caller “catches” these objects in separate
error handling routines. If you throw an exception, it cannot be ignored, so you can guarantee
that
something
will happen in response to your error.

(17) Run-time type identification.
Run-time type identification (RTTI) lets you find the

following statements: You can freely use this file
for your own work (personal or commercial),
including modifications and distribution in
executable form only. Permission is granted to use
this file in classroom situations, including its
use in presentation materials, as long as the book
"Thinking in C++" is cited as the source.
Except in classroom situations, you cannot copy
and distribute this code; instead, the sole
distribution point is
(and official mirror sites) where it is
freely available. You cannot remove this
copyright and notice. You cannot distribute
modified versions of the source code in this
package. You cannot use this file in printed
media without the express permission of the
author. Bruce Eckel makes no representation about
the suitability of this software for any purpose.
It is provided "as is" without express or implied
warranty of any kind, including any implied
warranty of merchantability, fitness for a
particular purpose or non-infringement. The entire
risk as to the quality and performance of the
software is with you. Bruce Eckel and the
publisher shall not be liable for any damages
suffered by you or any third party as a result of
using or distributing software. In no event will
Preface 25
Bruce Eckel or the publisher be liable for any
lost revenue, profit, or data, or for direct,

not trying to dictate correct style via my examples; I have my own motivation for using the
style that I do. Because C++ is a free-form programming language, you can continue to use
whatever style you’re comfortable with.
The programs in this book are files that are automatically extracted from the text of the book,
which allows them to be tested to ensure they work correctly. (I use a special format on the
first line of each file to facilitate this extraction; the line begins with the characters ‘
/’ ‘/’

:’
and the file name and path information.) Thus, the code files printed in the book should all
work without compiler errors when compiled with an implementation that conforms to
Standard C++ (note that not all compilers support all language features). The errors that
should
cause compile-time error messages are commented out with the comment
//!
so they
can be easily discovered and tested using automatic means. Errors discovered and reported to
the author will appear first in the electronic version of the book (at
www.BruceEckel.com
)
and later in updates of the book. 5
Ibid.
Preface 26
One of the standards in this book is that all programs will compile and link without errors
(although they will sometimes cause warnings). To this end, some of the programs, which
only demonstrate a coding example and don’t represent stand-alone programs, will have
empty

Language support
Your compiler may not support all the features discussed in this book, especially if you don’t
have the newest version of your compiler. Implementing a language like C++ is a Herculean
task, and you can expect that the features will appear in pieces rather than all at once. But if
you attempt one of the examples in the book and get a lot of errors from the compiler, it’s not
necessarily a bug in the code or the compiler – it may simply not be implemented in your
particular compiler yet.
Seminars & CD Roms
My company provides public hands-on training seminars based on the material in this book.
Selected material from each chapter represents a lesson, which is followed by a monitored
exercise period so each student receives personal attention. Information and sign-up forms for
upcoming seminars can be found at

. If you have specific
questions, you may direct them to

.
Preface 27
Errors
No matter how many tricks a writer uses to detect errors, some always creep in and these
often leap off the page for a fresh reader. If you discover anything you believe to be an error,
please use the correction form you will find at

. Your help is
appreciated.
Acknowledgements
The ideas and understanding in this book have come from many sources: friends like Dan
Saks, Scott Meyers, Charles Petzold, and Michael Wilk; pioneers of the language like Bjarne
Stroustrup, Andrew Koenig, and Rob Murray; members of the C++ Standards Committee like
Nathan Myers (who was particularly helpful and generous with his insights), Tom Plum, Reg

Todd, and their families. And of course, Mom & Dad.
29
1: Introduction
to objects
The genesis of the computer revolution was in a machine.
The genesis of our programming languages thus tends to
look like that machine.
But computers are not so much machines as they are mind amplification tools (“bicycles for
the mind,” as Steve Jobs is fond of saying) and a different kind of expressive medium. As a
result, the tools are beginning to look less like machines and more like parts of our minds, and
also like other expressive mediums such as writing, painting, sculpture, animation and
filmmaking. Object-oriented programming is part of this movement toward the computer as
an expressive medium.
This chapter will introduce you to the basic concepts of object-oriented programming (OOP),
including an overview of OOP development methods. This chapter, and this book, assume
you have had experience in some programming language, although not necessarily C. If you
feel you need more preparation in programming and the syntax of C before tackling this book,
you may want to consider MindView’s “Thinking in C: Foundations for C++ and Java”
training CD ROM, available at .
This chapter is background and supplementary material. Many people do not feel comfortable
wading into object-oriented programming without understanding the big picture first. Thus,
there are many concepts that are introduced here to give you a solid overview of OOP.
However, many other people don’t get the big picture concepts until they’ve seen some of the
mechanics first; these people may become bogged down and lost without some code to get
their hands on. If you’re part of this latter group and are eager to get to the specifics of the
language, feel free to jump past this chapter – skipping it at this point will not prevent you
from writing programs or learning the language. However, you will want to come back here
eventually, to fill in your knowledge so that you can understand why objects are important
and how to design with them.
The progress of abstraction


Nhờ tải bản gốc
Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status