Đây là quyển sách tiếng anh về lĩnh vực công nghệ thông tin cho sinh viên và những ai có đam mê. Quyển sách này trình về lý thuyết ,phương pháp lập trình cho ngôn ngữ C và C++.
Trang 2The Complete Reference
Third Edition
Trang 3C++ and a best-selling author whose bookshave sold more than 1.5 million copies His
acclaimed C and C++books include Teach
Yourself C, C++ from the Ground Up, Teach Yourself C++, C++: The Complete Reference, Borland C++: The Complete Reference, and C++ Programmer's Reference to name a few.
Trang 4C++: The Complete Reference
Paris São Paulo Singapore Sydney
Tokyo Toronto
Trang 5Copyright © 1998 by McGraw-Hill Companies All rights reserved Manufactured in the United States of America Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means,
or stored in a database or retrieval system, without the prior written permission of the publisher
0-07-213293-0
The material in this eBook also appears in the print version of this title: 0-07-882476-1
All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate ing programs For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-
train-4069
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms
THE WORK IS PROVIDED “AS IS” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS
TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless
of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, spe- cial, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim
or cause arises in contract, tort or otherwise.
DOI: 10.1036/0072132930
abc
Trang 6Contents at a Glance
Part I The Foundation of C++: The C Subset
1 An Overview of C 3
2 Expressions 13
3 Statements 57
4 Arrays and Null-Terminated Strings 89
5 Pointers 113
6 Functions 137
7 Structures, Unions, Enumerations, and User-Defined Types 161
8 C-Style Console I/O 187
9 File I/O 211
10 The Preprocessor and Comments 237
Part II C++ 11 An Overview of C++ 255
12 Classes and Objects 289
13 Arrays, Pointers, References and the Dynamic Allocation Operators 327
14 Function Overloading, Copy Constructors, and Default Arguments 361
15 Operator Overloading 385
v
Trang 716 Inheritance 419
17 Virtual Functions and Polymorphism 445
18 Templates 461
19 Exception Handling 489
20 C++ I/O System Basics 511
21 C++ File I/O 541
22 Run-Time Type ID and the Casting Operators 569
23 Namespaces, Conversion Functions,and Other Advanced Topics 593
24 Introducing the Standard Template Library 625
Part III The Standard Function Library 25 The C-Based I/O Functions 695
26 The String and Character Functions 719
27 The Mathematical Functions 733
28 Time, Date, and Localization Functions 743
29 The Dynamic Allocation Functions 753
30 Utility Functions 757
31 The Wide-Character Functions 771
Part IV The Standard C++ Class Library 32 The Standard C++ I/O Classes 783
33 The STL Container Classes 807
34 The STL Algorithms 835
35 STL Iterators, Allocators, and Function Objects 857
36 The String Class 877
37 The Numeric Classes 893
38 Exception Handling and Miscellaneous Classes 921
Part V Applying C++ 39 Integrating New Classes: A Custom String Class 931
40 An Object-Oriented Expression Parser 959
Index 995
Trang 8Preface xxix
Part I The Foundation of C++: The C Subset 1 An Overview of C 3
The Origins of C 4
C Is a Middle-Level Language 4
C Is a Structured Language 6
C Is a Programmer's Language 8
The Form of a C Program 9
The Library and Linking 10
Separate Compilation 12
Understanding the C and CPP File Extensions 12
2 Expressions 13
The Five Basic Data Types 14
vii
Trang 9Modifying the Basic Types 15
Identifier Names 16
Variables 17
Where Variables Are Declared 17
Local Variables 17
Formal Parameters 21
Global Variables 21
Access Modifiers 23
const 23
volatile 24
Storage Class Specifiers 25
extern 25
static Variables 27
register Variables 29
Variable Initializations 31
Constants 31
Hexadecimal and Octal Constants 32
String Constants 33
Backslash Character Constants 33
Operators 34
The Assignment Operator 34
Type Conversion in Assignments 35
Multiple Assignments 36
Arithmetic Operators 37
Increment and Decrement 37
Relational and Logical Operators 39
Bitwise Operators 42
The ? Operator 47
The & and * Pointer Operators 47
The Compile-Time Operator sizeof 49
The Comma Operator 50
The Dot (.) and Arrow (−>) Operators 51
The [ ] and ( ) Operators 51
Precedence Summary 52
Expressions 53
Order of Evaluation 53
Type Conversion in Expressions 53
Casts 54
Spacing and Parentheses 55
Shorthand Assignments 56
3 Statements 57
True and False in C and C++ 58
Trang 10Selection Statements 59
if 59
Nested ifs 60
The if-else-if Ladder 62
The ? Alternative 63
The Conditional Expression 66
switch 67
Nested switch Statements 70
Iteration Statements 70
The for Loop 70
for Loop Variations 72
The Infinite Loop 76
for Loops with No Bodies 77
The while Loop 77
The do-while Loop 79
Declaring Variables within Selection and Iteration Statements 81
Jump Statements 82
The return Statement 82
The goto Statement 83
The break Statement 83
The exit( ) Function 85
The continue Statement 86
Expression Statements 88
Block Statements 88
4 Arrays and Null-Terminated Strings 89
Single-Dimension Arrays 90
Generating a Pointer to an Array 92
Passing Single-Dimension Arrays to Functions 92
Null-Terminated Strings 94
Two-Dimensional Arrays 96
Arrays of Strings 100
Multidimensional Arrays 101
Indexing Pointers 102
Array Initialization 105
Unsized Array Initializations 106
A Tic-Tac-Toe Example 108
5 Pointers 113
What Are Pointers? 114
Pointer Variables 115
The Pointer Operators 115
Pointer Expressions 116
Trang 11Pointer Assignments 117
Pointer Arithmetic 117
Pointer Comparisons 119
Pointers and Arrays 120
Arrays of Pointers 122
Multiple Indirection 123
Initializing Pointers 124
Pointers to Functions 126
C's Dynamic Allocation Functions 129
Problems with Pointers 131
6 Functions 137
The General Form of a Function 138
Scope Rules of Functions 138
Function Arguments 139
Call by Value, Call by Reference 139
Creating a Call by Reference 140
Calling Functions with Arrays 142
argc and argv—Arguments to main( ) 144
The return Statement 147
Returning from a Function 147
Returning Values 149
Returning Pointers 151
Functions of Type void 152
What Does main( ) Return? 153
Recursion 153
Function Prototypes 155
Standard Library Function Prototypes 157
Declaring Variable-Length Parameter Lists 158
Old-Style Versus Modern Function Parameter Declarations 158
Implementation Issues 159
Parameters and General-Purpose Functions 159
Efficiency 159
7 Structures, Unions, Enumerations, and User-Defined Types 161
Structures 162
Accessing Structure Members 165
Structure Assignments 165
Arrays of Structures 166
Passing Structures to Functions 166
Passing Structure Members to Functions 167
Passing Entire Structures to Functions 167
Trang 12Structure Pointers 169
Declaring a Structure Pointer 170
Using Structure Pointers 170
Arrays and Structures Within Structures 173
Bit-Fields 174
Unions 176
Enumerations 180
Using sizeof to Ensure Portability 183
typedef 184
8 C-Style Console I/O 187
An Important Application Note 188
Reading and Writing Characters 189
A Problem with getchar( ) 190
Alternatives to getchar( ) 190
Reading and Writing Strings 192
Formatted Console I/O 195
printf( ) 195
Printing Characters 196
Printing Numbers 196
Displaying an Address 198
The %n Specifier 198
Format Modifiers 199
The Minimum Field Width Specifier 199
The Precision Specifier 200
Justifying Output 201
Handling Other Data Types 202
The * and # Modifiers 202
scanf( ) 203
Format Specifiers 203
Inputting Numbers 203
Inputting Unsigned Integers 205
Reading Individual Characters Using scanf( ) 205
Reading Strings 205
Inputting an Address 206
The %n Specifier 206
Using a Scanset 206
Discarding Unwanted White Space 207
Non-White-Space Characters in the Control String 208
You Must Pass scanf( ) Addresses 208
Format Modifiers 208
Suppressing Input 209
Trang 139 File I/O 211
C Versus C++ File I/O 212
Streams and Files 212
Streams 212
Text Streams 213
Binary Streams 213
Files 213
File System Basics 214
The File Pointer 215
Opening a File 215
Closing a File 217
Writing a Character 218
Reading a Character 218
Using fopen( ), getc( ), putc( ), and fclose( ) 218
Using feof( ) 220
Working with Strings: fputs( ) and fgets( ) 222
rewind( ) 223
ferror( ) 224
Erasing Files 226
Flushing a Stream 227
fread( ) and fwrite( ) 227
Using fread( ) and fwrite( ) 228
fseek( ) and Random-Access I/O 229
fprintf( ) and fscanf( ) 231
The Standard Streams 232
The Console I/O Connection 234
Using freopen( ) to Redirect the Standard Streams 235
10 The Preprocessor and Comments 237
The Preprocessor 238
#define 238
Defining Function-like Macros 240
#error 241
#include 242
Conditional Compilation Directives 242
#if, #else, #elif, and #endif 243
#ifdef and #ifndef 245
#undef 246
Using defined 247
#line 248
#pragma 248
The # and ## Preprocessor Operators 248
Predefined Macro Names 250
Trang 14C-Style Comments 250
Part II C++ 11 An Overview of C++ 255
The Origins of C++ 256
What Is Object-Oriented Programming? 257
Encapsulation 258
Polymorphism 258
Inheritance 259
Some C++ Fundamentals 259
A Sample C++ Program 260
A Closer Look at the I/O Operators 263
Declaring Local Variables 264
No Default to int 265
The bool Data Type 266
Old-Style vs Modern C++ 266
The New C++ Headers 268
Namespaces 269
Working with an Old Compiler 270
Introducing C++ Classes 270
Function Overloading 274
Operator Overloading 278
Inheritance 278
Constructors and Destructors 283
The C++ Keywords 287
The General Form of a C++ Program 288
12 Classes and Objects 289
Classes 290
Structures and Classes Are Related 293
Unions and Classes Are Related 295
Anonymous Unions 297
Friend Functions 298
Friend Classes 302
Inline Functions 303
Defining Inline Functions Within a Class 306
Parameterized Constructors 307
Constructors with One Parameter: A Special Case 309
Static Class Members 310
Static Data Members 310
Trang 15Static Member Functions 315
When Constructors and Destructors Are Executed 317
The Scope Resolution Operator 319
Nested Classes 320
Local Classes 320
Passing Objects to Functions 321
Returning Objects 323
Object Assignment 324
13 Arrays, Pointers, References, and the Dynamic Allocation Operators 327
Arrays of Objects 328
Creating Initialized vs Uninitialized Arrays 330
Pointers to Objects 331
Type Checking C++ Pointers 333
The this Pointer 334
Pointers to Derived Types 336
Pointers to Class Members 339
References 341
Reference Parameters 341
Passing References to Objects 345
Returning References 346
Independent References 347
References to Derived Types 348
Restrictions to References 349
A Matter of Style 349
C++'s Dynamic Allocation Operators 349
Initializing Allocated Memory 351
Allocating Arrays 352
Allocating Objects 353
The nothrow Alternative 358
The Placement Forms of new and delete 359
14 Function Overloading, Copy Constructors, and Default Arguments 361
Function Overloading 362
Overloading Constructor Functions 364
Overloading a Constructor to Gain Flexibility 364
Allowing Both Initialized and Uninitialized Objects 366
Copy Constructors 368
Finding the Address of an Overloaded Function 372
The overload Anachronism 373
Trang 16Default Function Arguments 374
Default Arguments vs Overloading 378
Using Default Arguments Correctly 380
Function Overloading and Ambiguity 380
15 Operator Overloading 385
Creating a Member Operator Function 386
Creating Prefix and Postfix Forms of the Increment and Decrement Operators 391
Overloading the Shorthand Operators 392
Operator Overloading Restrictions 392
Operator Overloading Using a Friend Function 393
Using a Friend to Overload ++ or – – 395
Friend Operator Functions Add Flexibility 398
Overloading new and delete 400
Overloading new and delete for Arrays 405
Overloading the nothrow Version of new and delete 408
Overloading Some Special Operators 409
Overloading [ ] 409
Overloading ( ) 413
Overloading –> 415
Overloading the Comma Operator 416
16 Inheritance 419
Base-Class Access Control 420
Inheritance and protected Members 422
Protected Base-Class Inheritance 426
Inheriting Multiple Base Classes 427
Constructors, Destructors, and Inheritance 428
When Constructor and Destructor Functions Are Executed 428
Passing Parameters to Base-Class Constructors 432
Granting Access 436
Virtual Base Classes 439
17 Virtual Functions and Polymorphism 445
Virtual Functions 446
Calling a Virtual Function Through a Base Class Reference 449
The Virtual Attribute Is Inherited 450
Virtual Functions Are Hierarchical 452
Pure Virtual Functions 455
Abstract Classes 457
Trang 17Using Virtual Functions 457
Early vs Late Binding 460
18 Templates 461
Generic Functions 462
A Function with Two Generic Types 465
Explicitly Overloading a Generic Function 465
Overloading a Function Template 468
Using Standard Parameters with Template Functions 468
Generic Function Restrictions 469
Applying Generic Functions 470
A Generic Sort 471
Compacting an Array 472
Generic Classes 474
An Example with Two Generic Data Types 478
Applying Template Classes: A Generic Array Class 479
Using Non-Type Arguments with Generic Classes 481
Using Default Arguments with Template Classes 483
Explicit Class Specializations 485
The typename and export Keywords 486
The Power of Templates 487
19 Exception Handling 489
Exception Handling Fundamentals 490
Catching Class Types 496
Using Multiple catch Statements 497
Handling Derived-Class Exceptions 499
Exception Handling Options 500
Catching All Exceptions 500
Restricting Exceptions 502
Rethrowing an Exception 504
Understanding terminate( ) and unexpected( ) 505
Setting the Terminate and Unexpected Handlers 506
The uncaught_exception( ) Function 507
The exception and bad_exception Classes 508
Applying Exception Handling 508
20 The C++ I/O System Basics 511
Old vs Modern C++ I/O 512
C++ Streams 513
The C++ Stream Classes 513
C++'s Predefined Streams 514
Formatted I/O 515
Trang 18Formatting Using the ios Members 515
Setting the Format Flags 516
Clearing Format Flags 517
An Overloaded Form of setf( ) 518
Examining the Formatting Flags 520
Setting All Flags 521
Using width( ), precision( ), and fill( ) 522
Using Manipulators to Format I/O 524
Overloading << and >> 528
Creating Your Own Inserters 528
Creating Your Own Extractors 534
Creating Your Own Manipulator Functions 537
21 C++ File I/O 541
<fstream> and the File Classes 542
Opening and Closing a File 542
Reading and Writing Text Files 545
Unformatted and Binary I/O 547
Characters vs Bytes 547
put( ) and get( ) 548
read( ) and write( ) 550
More get( ) Functions 553
getline( ) 553
Detecting EOF 555
The ignore( ) Function 557
peek( ) and putback( ) 558
flush( ) 558
Random Access 559
Obtaining the Current File Position 563
I/O Status 563
Customized I/O and Files 565
22 Run-Time Type ID and the Casting Operators 569
Run-Time Type Identification (RTTI) 570
A Simple Application of Run-Time Type ID 576
typeid Can Be Applied to Template Classes 578
The Casting Operators 580
dynamic_cast 580
Replacing typeid with dynamic_cast 584
Using dynamic_cast with Template Classes 586
const_cast 588
static_cast 590
reinterpret_cast 590
Trang 1923 Namespaces, Conversion Functions,
and Other Advanced Topics 593
Namespaces 594
Namespace Fundamentals 594
using 598
Unnamed Namespaces 600
Some Namespace Options 601
The std Namespace 603
Creating Conversion Functions 605
const Member Functions and mutable 609
Volatile Member Functions 611
Explicit Constructors 612
Using the asm Keyword 613
Linkage Specification 614
Array-Based I/O 615
The Array-Based Classes 616
Creating an Array-Based Output Stream 616
Using an Array as Input 618
Input/Output Array-Based Streams 620
Using Dynamic Arrays 621
Using Binary I/O with Array-Based Streams 622
Summarizing the Differences Between C and C++ 623
24 Introducing the Standard Template Library 625
An Overview of the STL 626
Containers 626
Algorithms 627
Iterators 627
Other STL Elements 628
The Container Classes 629
General Theory of Operation 630
Vectors 631
Accessing a Vector Through an Iterator 635
Inserting and Deleting Elements in a Vector 637
Storing Class Objects in a Vector 639
Lists 641
Understanding end( ) 645
push_front( ) vs push_back( ) 647
Sort a List 648
Merging One List with Another 649
Storing Class Objects in a List 651
Maps 654
Trang 20Storing Class Objects In a Map 658
Algorithms 660
Counting 660
Removing and Replacing Elements 666
Reversing a Sequence 668
Transforming a Sequence 669
Using Function Objects 671
Unary and Binary Function Objects 671
Using the Built-in Function Objects 671
Creating a Function Object 674
Using Binders 676
The string Class 679
Some string Member Functions 683
Strings Are Containers 689
Putting Strings into Other Containers 690
Final Thoughts on the STL 691
Part III The Standard Function Library 25 The C-Based I/O Functions 695
clearerr 696
fclose 697
feof 697
ferror 697
fflush 698
fgetc 698
fgetpos 698
fgets 699
fopen 699
fprintf 701
fputc 701
fputs 702
fread 702
freopen 702
fscanf 703
fseek 703
fsetpos 704
ftell 704
fwrite 705
getc 705
getchar 706
gets 706
Trang 21perror 706
printf 707
putc 710
putchar 710
puts 710
remove 711
rename 711
rewind 711
scanf 711
setbuf 715
setvbuf 715
sprintf 716
sscanf 716
tmpfile 716
tmpnam 717
ungetc 717
vprintf, vfprintf, and vsprintf 718
26 The String and Character Functions 719
isalnum 720
isalpha 720
iscntrl 721
isdigit 721
isgraph 721
islower 721
isprint 722
ispunct 722
isspace 722
isupper 723
isxdigit 723
memchr 723
memcmp 723
memcpy 724
memmove 724
memset 725
strcat 725
strchr 725
strcmp 726
strcoll 726
strcpy 727
strcspn 727
strerror 727
strlen 727
Trang 23localtime 748mktime 748setlocale 748strftime 749time 750
29 The Dynamic Allocation Functions 753
calloc 754free 754malloc 755realloc 755
30 Utility Functions 757
abort 758abs 758assert 759atexit 759atof 759atoi 760atol 760bsearch 760div 761exit 762getenv 762labs 762ldiv 763longjmp 763mblen 763mbstowcs 764mbtowc 764qsort 764raise 765rand 766setjmp 766signal 766srand 767strtod 767strtol 768strtoul 768system 769va_arg, va_start, and va_end 769wcstombs 770wctomb 770
Trang 2431 The Wide-Character Functions 771
The Wide-Character Classification Functions 772
The Wide-Character I/O Functions 775
The Wide-Character String Functions 775
Wide-Character String Conversion Functions 775
Wide-Character Array Functions 778
Multibyte/Wide-Character Conversion Functions 779
Part IVThe Standard C++ Class Library
32 The Standard C++ I/O Classes 783
The I/O Classes 784
The I/O Headers 786
The Format Flags and I/O Manipulators 787
Several Data Types 789
The streamsize and streamoff Types 789
The streampos and wstreampos Types 789
The pos_type and off_type Types 789
The openmode Type 789
The iostate Type 790
The seekdir type 790
The failure Class 790
Overload << and >> Operators 790
The General-Purpose I/O Functions 791
Trang 25put 798putback 798rdstate 798read 799readsome 799seekg and seekp 800setf 801setstate 801str 802stringstream, istringstream, ostringstream 802sync_with_stdio 803tellg and tellp 804unsetf 804width 804write 805
33 The STL Container Classes 807
The Container Classes 808
bitset 810deque 812list 815map 818multimap 820multiset 823queue 825priority_queue 826set 827stack 829vector 830
34 The STL Algorithms 835
adjacent_find 836binary_search 836copy 837copy_backward 837count 837count_if 838equal 838equal_range 838fill and fill_n 839find 839find_end 839find_first_of 839
Trang 26remove, remove_if, remove_copy, and remove_copy_if 848
replace, replace_copy, replace_if, and replace_copy_if 848
reverse and reverse_copy 849
rotate and rotate_copy 849
Trang 2735 STL Iterators, Allocators, and Function Objects 857
Iterators 858
The Basic Iterator Types 858The Low-Level Iterator Classes 859The Predefined Iterators 860Two Iterator Functions 868Function Objects 868
Function Objects 869Binders 870Negators 871Adaptors 872Allocators 875
36 The String Class 877
The basic_string Class 878The char_traits Class 890
37 The Numeric Classes 893
The complex Class 894The valarray Class 898
The slice and gslice Classes 913The Helper Classes 916The Numeric Algorithms 916
accumulate 916adjacent_difference 917inner_product 918partial_sum 919
38 Exception Handling and Miscellaneous Classes 921
Exceptions 922
<exception> 922
<stdexcept> 923auto_ptr 924The pair Class 926Localization 927Other Classes of Interest 927
Part VApplying C++
39 Integrating New Classes: A Custom String Class 931
The StrType Class 932
Trang 28The Constructor and Destructor Functions 934
I/O on Strings 935
The Assignment Functions 937
Concatenation 938
Substring Subtraction 941
The Relational Operators 943
Miscellaneous String Functions 944
The Entire StrType Class 945
Using the StrType Class 954
Creating and Integrating New Types in General 957
A Simple Expression Parser 967
Understanding the Parser 973
Adding Variables to the Parser 974
Syntax Checking in a Recursive-Descent Parser 984
Building a Generic Parser 985
Some Things to Try 993
Index 995
Trang 30This is the third edition of C++: The Complete Reference In the years that have transpired
since the second edition, C++ has undergone many changes Perhaps the most important
is that it is now a standardized language In November of 1997, the ANSI/ISO
committee charged with the task of standardizing C++, passed out of committee anInternational Standard for C++ This event marked the end of a very long, and attimes contentious, process As a member of the ANSI/ISO C++ committee, I watchedthe progress of the emerging standard, following each debate and argument Near theend, there was a world-wide, daily dialogue, conducted via e-mail, in which the prosand cons of this or that issue were put forth, and finally resolved While the processwas longer and more exhausting than anyone at first envisioned, the result was worththe trouble We now have a standard for what is, without question, the most importantprogramming language in the world
During standardization, several new features were added to C++ Some are
relatively small Others, like the STL (Standard Template Library) have ramificationsthat will affect the course of programming for years to come The net effect of theadditions was that the scope and range of the language were greatly expanded Forexample, because of the addition of the numerics library, C++ can be more convenientlyused for numeric processing Of course, the information contained in this edition
xxix
Trang 31reflects the International Standard for C++ defined by the ANSI/ISO committee,including its new features.
What's New in the Third Edition
The third edition of C++: The Complete Reference is greatly expanded beyond its
predecessor In fact, the length of the book has nearly doubled! The main reason forthis is that the third edition now includes comprehensive coverage of both the standardfunction library and the standard class library Neither of these were sufficiently welldefined when the second edition was being prepared to warrant inclusion With thestandardization of C++ being complete, these topics can finally be added
Aside from these major additions, the third edition also includes a substantialamount of new material scattered throughout the book Most is the result of featuresthat have been added to C++ since the previous edition was prepared New or
expanded coverage includes the following topics: the Standard Template Library,run-time type ID (RTTI), the new casting operators, new features of templates,
namespaces, new-style headers, and the modern-style I/O system Also, some
fundamental changes to the way new and delete are implemented are described and
several new keywords are discussed
Frankly, if you have not taken a close look at C++ for the past few years, you will
be surprised at how much it has grown and how many new features have been added.It's not the same old C++ that you learned years ago
■ The Standard Function Library
■ The Standard Class Library
■ Sample C++ applications
Part One provides a comprehensive discussion of the C subset of C++ As mostreaders will know, C is the foundation upon which C++ was built It is the C subset
that defines the bedrock features of C++, including such things as for loops and if
statements It also defines the essential nature of C++'s block structure, pointers, andfunctions Since many readers are already familiar with and proficient in C, discussingthe C subset separately in Part One prevents the knowledgeable C programmer fromhaving to "wade through" reams of information he or she already knows Instead, the
Trang 32experienced C programmer can simply turn to the sections of this book that cover the
C++-specific features
Part Two discusses in detail the extensions and enhancements to C added by C++
These include its object-oriented features such as classes, constructors, destructors, and
templates Thus, Part Two covers those constructs that "make C++, C++."
Part Three describes the standard function library and Part Four examines the
standard class library, including the STL (Standard Template Library) Part Five shows
two practical examples of applying C++ and object-oriented programming
A Book for All Programmers
This C++ reference is designed for all C++ programmers, regardless of their experience
level It does assume, however, a reader able to create at least a simple program If you
are just learning C++, this book will make an excellent companion to any C++ tutorial
and serve as a source of answers to your specific questions Experienced C++ pros will
find the coverage of the many new features added by the International Standard
especially useful
If You're Using Windows
If your computer uses Windows, then you have chosen the right language C++ is
completely at home with Windows programming However, none of the programs
in this book are Windows programs Instead, they are console-based programs The
reason for this is easy to understand: Windows programs are, by their nature, large and
complex The overhead required to create even a minimal Windows skeletal program
is 50 to 70 lines of code To write Windows programs that demonstrate the features of
C++ would require hundreds of lines of code each Put simply, Windows is not an
appropriate environment in which to discuss the features of a programming language
However, you can still use a Windows-based compiler to compile the programs in this
book because the compiler will automatically create a console session in which to
execute your program
Don't Forget: Code On The Web
Remember, the source code for all of the programs in this book is available
free-of-charge on the Web at http://www.osborne.com Downloading this code
prevents you from having to type in the examples
Trang 33For Further Study
C++: The Complete Reference is your gateway into the "Herb Schildt" series of
programming books Here is a partial list of Schildt's other books
If you want to learn more about C++, then you will find these books especiallyhelpful
C++ From the Ground Up
Teach Yourself C++
Expert C++
If you want to learn more about C, the foundation of C++, we recommend
Teach Yourself C
C: The Complete Reference
The Annotated ANSI C Standard
If you will be developing programs for the Web, you will want to read
Java: The Complete Reference
co-authored by Herbert Schildt and Patrick Naughton
Finally, if you want to program for Windows, we recommend
Windows 98 Programming From the Ground Up
Windows NT 4 From the Ground Up
MFC Programming From the Ground Up
When you need solid answers, fast, turn to Herbert Schildt,
the recognized authority on programming.
Trang 34Part I
The Foundation of C++:
The C Subset
T his book divides the description of the C++ language into
two parts Part One discusses the C-like features of C++.
This is commonly referred to as the C subset of C++ Part Two
describes those features specific to C++ Together, they describe the entire C++ language.
As you may know, C++ was built upon the foundation of C.
In fact, C++ includes the entire C language, and (with minor exceptions) all C programs are also C++ programs When C++ was invented, the C language was used as the starting point To C were added several new features and extensions designed to
1
Trang 35support object-oriented programming (OOP) However, the C-like aspects of
C++ were never abandoned, and the ANSI/ISO C standard is a base document for
the International Standard for C++ Thus, an understanding of C++ implies an
understanding of C
In a book such as this Complete Reference, dividing the C++ language into two
pieces—the C foundation and the C++-specific features—achieves three major benefits:
1 The dividing line between C and C++ is clearly delineated
2 Readers already familiar with C can easily find the C++-specific information
3 It provides a convenient place in which to discuss those features of C++ thatrelate mostly to the C subset
Understanding the dividing line between C and C++ is important because both arewidely used languages and it is very likely that you will be called upon to write ormaintain both C and C++ code When working on C code, you need to know where Cends and C++ begins Many C++ programmers will, from time to time, be required towrite code that is limited to the "C subset." This will be especially true for embeddedsystems programming and the maintenance of existing applications Knowing thedifference between C and C++ is simply part of being a top-notch professional C++programmer
A clear understanding of C is also valuable when converting C code into C++ To
do this in a professional manner, a solid knowledge of C is required For example,without a thorough understanding of the C I/O system, it is not possible to efficientlyconvert an I/O-intensive C program into C++
Many readers already know C Covering the C-like features of C++ in their ownsection makes it easier for the experienced C programmer to quickly and easily findinformation about C++ without having to wade through reams of information that he
or she already knows Of course, throughout Part One, any minor differences between
C and C++ are noted Also, separating the C foundation from the more advanced,object-oriented features of C++ makes it possible to tightly focus on those advancedfeatures because all of the basics will have already been discussed
Although C++ contains the entire C language, not all of the features provided bythe C language are commonly used when writing "C++-style" programs For example,the C I/O system is still available to the C++ programmer even though C++ defines itsown, object-oriented version The preprocessor is another example The preprocessor isvery important to C, but less so to C++ Discussing several of the "C-only" features inPart One prevents them from cluttering up the remainder of the book
The C subset described in Part One constitutes the core of C++ and the foundation upon which C++'s object-oriented features are built All the features described here are part of C++ and available for your use.
Part One of this book is adapted from my book C: The Complete Reference (Osborne/McGraw-Hill) If you are particularly interested in C, you will find this book helpful.
Note
Remember
Trang 36Chapter 1
An Overview of C
3
C++
Trang 37To understand C++ is to understand the forces that drove its creation, the ideas
that shaped it, and the legacy it inherits Thus, the story of C++ begins with C.This chapter presents an overview of the C programming language, its origins, itsuses, and its underlying philosophy Since C++ is built upon C, this chapter provides
an important historical perspective on the roots of C++ Much of what makes C++what it is had its genesis in the C language
The Origins of C
C was invented and first implemented by Dennis Ritchie on a DEC PDP-11 that usedthe Unix operating system C is the result of a development process that started with anolder language called BCPL BCPL was developed by Martin Richards, and it
influenced a language called B, which was invented by Ken Thompson B led to thedevelopment of C in the 1970s
For many years, the de facto standard for C was the version supplied with the Unix
version 5 operating system It was first described in The C Programming Language by
Brian Kernighan and Dennis Ritchie (Englewood Cliffs, N.J.: Prentice-Hall, 1978) In thesummer of 1983 a committee was established to create an ANSI (American NationalStandards Institute) standard that would define the C language once and for all Thestandardization process took six years (much longer than anyone reasonably expected).The ANSI C standard was finally adopted in December 1989, with the first copiesbecoming available in early 1990 The standard was also adopted by ISO (InternationalStandards Organization) and is now referred to as the ANSI/ISO C standard For
simplicity, this book will use the term Standard C when referring to the ANSI/ISO C
standard Today, all mainstream C/C++ compilers comply with Standard C Standard
C is the foundation upon which C++ is built
C Is a Middle-Level Language
C is often called a middle-level computer language This does not mean that C is less
powerful, harder to use, or less developed than a high-level language such as BASIC
or Pascal, nor does it imply that C has the cumbersome nature of assembly language(and its associated troubles) Rather, C is thought of as a middle-level language because
it combines the best elements of high-level languages with the control and flexibilityofassembly language Table 1-1 shows how C fits into the spectrum of computer
languages
As a middle-level language, C allows the manipulation of bits, bytes, and
addresses—the basic elements with which the computer functions Despite this fact
C code is also very portable Portability means that it is easy to adapt software written
for one type of computer or operating system to another For example, if you can easilyconvert a program written for DOS so that it runs under Windows, that program isportable
Trang 38All high-level programming languages support the concept of data types A data
type defines a set of values that a variable can store along with a set of operations that
can be performed on that variable Common data types are integer, character, and real.Although C has five basic built-in data types, it is not a strongly typed language, as arePascal and Ada C permits almost all type conversions For example, you may freely
intermix character and integer types in an expression
Unlike a high-level language, C performs almost no run-time error checking For
example, no check is performed to ensure that array boundaries are not overrun Thesetypes of checks are the responsibility of the programmer
In the same vein, C does not demand strict type compatibility between a parameterand an argument As you may know from your other programming experience, a
high-level computer language will typically require that the type of an argument be
(more or less) exactly the same type as the parameter that will receive the argument
However, such is not the case for C Instead, C allows an argument to be of any type
as long as it can be reasonably converted into the type of the parameter Further, C
provides all of the automatic conversions to accomplish this
Modula-2PascalCOBOLFORTRANBASIC
C++
CFORTH
Assembler
Table 1-1 C's Place in the World of Programming Languages
Trang 39C is special in that it allows the direct manipulation of bits, bytes, words, andpointers This makes it well suited for system-level programming, where these
operations are common
Another important aspect of C is that it has only 32 keywords (27 from the
Kernighan and Ritchie de facto standard, and five added by the ANSI standardizationcommittee), which are the commands that make up the C language High-level
languages typically have several times more keywords As a comparison, considerthat most versions of BASIC have well over 100 keywords!
C Is a Structured Language
In your previous programming experience, you may have heard the term
block-structured applied to a computer language Although the term block-block-structured
language does not strictly apply to C, C is commonly referred to simply as a
structured language It has many similarities to other structured languages, such
as ALGOL, Pascal, and Modula-2
The reason that C (and C++) is not, technically, a block-structured language is that block-structured languages permit procedures or functions to be declared inside other procedures or functions Since C does not allow the creation of functions within functions, it cannot formally be called block-structured.
The distinguishing feature of a structured language is compartmentalization of code
and data This is the ability of a language to section off and hide from the rest of theprogram all information and instructions necessary to perform a specific task Oneway that you achieve compartmentalization is by using subroutines that employ local(temporary) variables By using local variables, you can write subroutines so that theevents that occur within them cause no side effects in other parts of the program Thiscapability makes it very easy for programs to share sections of code If you developcompartmentalized functions, you only need to know what a function does, not how itdoes it Remember, excessive use of global variables (variables known throughout theentire program) may allow bugs to creep into a program by allowing unwanted sideeffects (Anyone who has programmed in standard BASIC is well aware of this
problem.)
The concept of compartmentalization is greatly expanded by C++ Specifically, in C++, one part of your program may tightly control which other parts of your program are allowed access.
A structured language allows you a variety of programming possibilities It
directly supports several loop constructs, such as while, do-while, and for In a structured language, the use of goto is either prohibited or discouraged and is not the
common form of program control (as is the case in standard BASIC and traditional
Note
Note
Trang 40FORTRAN, for example) A structured language allows you to place statements
anywhere on a line and does not require a strict field concept (as some older
language is that it is nonstructured Today, few programmers would consider using
a nonstructured language for serious, new programs
New versions of many older languages have attempted to add structured elements.
BASIC is an example However, the shortcomings of these languages can never be
fully mitigated because they were not designed with structured features from the
beginning.
C's main structural component is the function—C's stand-alone subroutine In
C, functions are the building blocks in which all program activity occurs They let
you define and code separately the separate tasks in a program, thus allowing your
programs to be modular After you have created a function, you can rely on it to
work properly in various situations without creating side effects in other parts of
the program Being able to create stand-alone functions is extremely critical in larger
projects where one programmer's code must not accidentally affect another's
Another way to structure and compartmentalize code in C is through the use of
code blocks A code block is a logically connected group of program statements that is
treated as a unit In C, you create a code block by placing a sequence of statements
between opening and closing curly braces In this example,