标准C++是最流行的面向对象程序设计(OOP)语言之一。本书将OOP的概念和方法融合在C++中,更重要的是说明如何将C++的各项功能综合运用,以达到OOP的目的。书中全面介绍了面向对象程序设计的重要概念,如数据抽象、封装、信息隐藏、继承和多态性等,同时还包含了C++语言的OOP方面的所有内容,包括类、操作符重载继承、模板等。此外,书中还描述了新的ANSIC++标准、模板库等。通过阅读本书,读者将对C++语言及面向对象程序设计有一个全面、深刻的了解。
本书特点:
为了使读者很快地掌握C++语言,本书前面的几章介绍了C++的基础知识,并且讨论了C++语言的一些基本特征为了加速读者学习本书的过程,书中还提供了许多编程技巧和推荐的编程风格等为了使本书易于在教学中使用,作者开发了许多有趣的例子和具有挑战性的习题书中的概念和编程结构都有足够的示例说明,按章组织的示例程序包大约有400个文件,包含了完整的源代码:
用于UNIX和PC的完整示例程序包可以在WWW.brookscole.com站点获得本书内容的组织和介绍均以简单。明确、易学为出发点,适合作为本科生程序设计课程的教材。
Paul S.Wang,于麻省理工学院(MIT)获得博士学位,现任肯特州立大学计算机科学系教授和计算数学研究所主任。他是国际著名的计算机科学家和资深顾问,发表过100多篇研究论文,并著有多本倍受赞誉的计算机科学书籍。作者网址为http://sofpower.com或http://monkey.cs.kent.edu/-pwang。
C++ is one of the most popular languages for object-oriented programming (OOP), the centerpiece of object technology (OT) that is revolutionizing the software industry. OOP creates programs that are well organized, easy to un-derstand and modify, flexible, and reusable in many different situations. It reduces complexity and makes software production and maintenance more economical. C++ has been standardized jointly by the International Standards Organization (ISO) and the American National Standards Institute (ANSI).
The ISO/ANSI C++ standard (ISO/IEC FDIS 14882) was approved in Novem-ber 1997.
New features introduced in Standard C++ include the Boolean type boot,exceptions, namespaces, run-time type identification, type cast notations, and template libraries with generic algorithms. Standard C++ also revised and extended a number of existing features including the wide character type,templates, and function call resolution. A new string class makes character strings easier to use.
This book is a revision of C++ with Object-Oriented Programming, covering Standard C++ comprehensively while preserving the proven approach. The C++ constructs are matched with clear and precise OOP concepts. Language mechanisms are explained individually and in combination to achieve OOP objectives. Object-based, object-oriented, and generic programming techniques are demonstrated in realistic programs to show their applications in practice.Chapter 12 shows how C++ can be applied for Web CGI programming.
OBJECT ORIENTATION C++ is important because it is efficient and supports OOP well. Thus, OOP concepts and techniques are taught as an integral part of C++ programming.The approach brings OOP concepts down to earth so that they are easily grasped. Object orientation is introduced early and demonstrated with many complete examples. How these techniques are applied to solve problems and how they make programs more flexible and reusable are dearly shown.
Key OOP concepts such as data abstraction, encapsulation, information hiding, problem solving with objects, genericness, inheritance, and polymor-phism are presented clearly and comprehensively. Basics on object-oriented design are also included. Again, these are illustrated by many C++ examples,including a bank account example that is carried through many chapters.
HANDS-ON APPROACH
The best way to learn programming is to write programs. With clear concepts and good examples, the text encourages the writing of interesting programs early. Chapters 1 and 2 form a primer introducing essential components of C++and object-based programming to get started quickly. Materials on thinking with objects, C++ programming tips, and style guides help beginning pro-grammers.
A pocket calculator simulation program is introduced in Chapter 5. This program evolves with each new chapter through programming exercises. Fi-nally, in Chapter 13, a substantial pocket calculator program emerges that connects many key OOP concepts and C++ constructs.
COMPREHENSIVE COVERAGE
Standard C++ is presented comprehensively and in depth. The coverage an- ticipates the needs of students and describes Standard C++ as an integral, self-contained language. The examples evolve as new material is covered, pro- viding many chances to revisit familiar code and to focus on the new concepts and features being introduced.
It is possible to use this book as the sole text for a course. Besides the basic topics, it covers the Standard Library, the I/O stream classes, templates, the Standard Template Library (STL), generic algorithms, program organization, use of header files, error and exception handling, preprocessing, and compila- tion (on UNIX and on PC).
Object orientation is emphasized with topics on building software ob- jects, comparing external behavior versus internal workings, reducing com- plexity with encapsulation, deriving new classes based on existing ones, writing generic codes that are reusable in many situations, creating soft-
ware black boxes that are plug-compatible in usage, and establishing poly- morphic procedures and objects that work with multiple types of objects.
Also included are object-oriented design techniques, methods, and applica- tions.
OOP MADE EASY
Standard C++ is a large and complex language. It is easy to get lost in the maze of new OOP concepts and the supporting C++ constructs. No effort is spared to make this complicated subject easy to grasp and understand. The approach begins with simple topics and key concepts as a foundation. Then, advanced topics are added in a logical sequence that is easy to follow. The materials are organized to anticipate questions and provide answers. Clear, interesting, and realistic examples show how to write object-oriented programs and how to apply the concepts and techniques introduced.
Inheritance, a key OOP feature, tends to be difficult for beginning pro-grammers. A clear mental picture is painted of a derived class and its relation with a base class upon which it is built. Furthermore, specific principles on class derivation and its proper usage are supplied. Multiple inheritance is also covered with clarity and good examples.
Polymorphism and plug compatibility are central OOP techniques that require sophistication to use well. An entire chapter is devoted to this subject that provides enough material to challenge even the most advanced students.
WEB APPLICATION
CGI programs written in C++ can be fast and efficient. HTML forms and CGI programs for form processing are presented in a concise chapter that puts the OOP concepts and C++ techniques to good use. A C++ class library for CGI programming is given and explained. CGI programs using this library for form processing are presented.
FLEXIBLE USAGE
The book contains more than enough material for a three-credit programming course at the junior, senior, or beginning graduate level. No C background is assumed, but appropriate programming experience, to appreciate software complexity, is highly recommended. Knowledge of C or ANSI C will reduce the amount of work involved. At a lower level, the material in the beginning chapters should be covered carefully. Advanced topics such as user-defined free storage management (Section 8.12), CGI programming (Chapter 12), and object-oriented design (Chapter 13) can be omitted. At a higher level,Chapter 1 and Chapter 14 can be assigned to students as background reading to more class time for other topics.
For a class with substantial programming experience, generic program- ming, template writing, and object-oriented programming projects, as sug- gested by the end-of-chapter exercises, can be emphasized. In this case, the design considerations covered in Chapter 13 may be discussed much earlier
The preprocessing and compilation material in Chapter 14 can be intro- duced (or assigned for reading by students) whenever the instructor feels it is appropriate in a course. Chapters 2 through 11 are central to this text and should prove challenging and rewarding to any reader
The book can also be used as a valuable supplement to a general course on OOP, data structures, or object-oriented design with C++ implementation.
RIGHT FOR YOUR SYSTEM
C++ is presented in a system-independent manner. The examples will run on any reasonable C++ implementation including workstations, PCs, and multi-user servers. Chapter 14 gives general information on preprocessing, compil-ing, and executing programs. The Free Software Foundation offers g++, a good implementation of C++ for free downloading:
http: //www. gnu. ai .mit. edu/software/gcc (for UNIX)
http://www.delorie.com/djgpp/ (for PC)
EASY REFERENCE
As an instructional guide, this text follows an incremental approach, whereby new concepts are built on old ones to make understanding easy. However,the book is also a valuable reference tool. Information has been organized for easy reference with tables, figures, displayed syntax explanations, examples,and summaries. All key C++ constructs are collected in Appendix A for quick review. Appendix B summarizes usage of special member functions. Other ap-pendices cover debugging, library functions, and the mixed use of C++ and C.Accurate cross-referencing and a comprehensive index help locate information contained in the book.
EXAMPLE PACKAGE
Throughout the text, concepts and programming constructs are amply illus-trated with examples of practical importance. The example package is orga-nized by chapter. There are about 400 files containing complete source codes that are ready to compile. The complete example package for UNIX and for PC is available from the Brooks/Cole Web site www. brookscole, com
ACKNOWLEDGMENTS
The book has benefited from the previous edition, extensive classroom use,and feedback from industry. In particular, I wish to thank W. B. Adams of Goodyear Tire and Rubber Company, Technical Computer Operations (Akron,Ohio). The book has gone through several rounds of reviews, and I would like to thank the following reviewers for their suggestions and corrections:
William G. Albrecht Florida Southern College
Richard Chang University of Maryland
Julius Dichter University of Bridgeport
Craig A. Adams Houston Community College System
Hristina Galabova Home Box Office, Inc.
Especially, I'd like to thank Hristina Galabova, a Kent State alumna, for her thorough review and thoughtful suggestions, resulting in many improve-ments.
The final draft of the book went through classroom trial at Kent State University in the spring of 2000. This resulted in many improvements. My ap-predation goes to all the students who took the Object-Oriented Programming class. Thanks also go to Joyce Fuell, my assistant at the Institute for Computa-tional Mathematics of the Department of Mathematics and Computer Science at Kent State University, for helping with the production of the manuscript.
I would like to thank Kallie Swanson, the editor at Brooks/Cole for her ex-pert handling of this publication, to Merrill Peterson at Matrix Productions for managing the production process, and to Arthur Ogawa at TEX Consultants for the LATEX style file, graphical art, index generation, and great composition.
My daughter Laura suggested the term appendant, and it proved to be very helpful in describing class derivation. She deserves all the credit. Finally, I'd like to thank my wife, Jennifer, and younger children, Deborah and David, for their understanding, support, and encouragement.
Paul S. Wang
Kent State University
Introduction 1
ONE C++ Primer Part 1: Basics 8
1.1 Object-Oriented Program Structure 8
1.2 Functions 9
1.3 Running the First Example 12
1.4 Statements 12
1.5 The while Statement 13
1.6 Simple Conditional Statements 16
1.7 Characters and Character Input and Output 17
1.8 More Basic Constructs 20
1.9 Data Types and Declarations 26
1.10 Operators and Expressions 29
1.11 Enumerations 35
1.12 Arrays 37
1.13 Pointers 40
1.14 An Example 41
1.15 Iteration Control 42
1.16 Choices by switch 46
1.17 Summary 48
Exercises 48
TWO C++ Primer Part II: Object-Based Programming 51
2.1 Data Abstraction and Encapsulation 51
2.2 Function Calls and Argument Passing 58
2.3 Command-Line Arguments 61
2.4 Environment Variables 62
2.5 The string Class 63
2.6 Problem Solving with Objects 65
2.7 C++ I/O Streams 70
2.8 Error Handling 70
2.9 Object-Based Thinking 73
2.10 C++ Programming Tips 74
2.11 Summary 77
Exercises 78
THREE Key Constructs 80
3.1 Identifier Scoping 81
3.2 Namespaces 84
3.3 More on Declarations 86
3.4 Recursion 89
3.5 A Class of Fractions 93
3.6 Optional and Variable-Length Arguments 97
3.7 Overloading Functions 99
3.8 References 102
3.9 Read-Only Variables and Parameters 103
3.10 The typedef Declaration 105
3.11 Storage Allocation and Management 106
3.12 A Circular Buffer 109
3.13 Implicit Type Conversions 114
3.14 Explicit Type Cast 116
3.15 HOW to Use Header Files 117
3.16 Summary 119
Exercises 120
FOUR Arrays, Pointers, and Generic Code 123
4.1 Array Concepts and Declarations 123
4.2 Pointers and Address Arithmetic 125
4.3 TWo-Dimensional Arrays 133
4.4 A Matrix Class 135
4.5 A Class of Polynomials 138
4.6 Array Objects: vector 141
4.7 Sorting Text Lines with Objects 143
4.8 Pointers and Function Calls 151
4.9 Arrays, Pointers, and References 154
4.10 Multiple Indirection 154
4.11 Generic Programs 156
4.12 A Generic Sorting Program 162
4.13 Pointers and Dynamically Allocated Storage 165
4.14 Summary 168
Exercises 169
FIVE Classes and Objects 172
5.1 Defining Classes 172
5.2 Creating and Initializing Objects 175
5.3 The Host Object 181
5.4 Internal-External Decoupling 182
5.5 Pocket Calculator Simulation 183
5.6 Built-in Operations for Objects 192
5.7 Object Destruction 193
5.8 Friends of a Class 195
5.9 Recursive Structures 197
5.10 Instance and Static Members 204
5.11 The Size of Objects 210
5.12 Generic Lists 211
5.13 Unions and Bit Fields 216
5.14 Summary 216
Exercises 217
six I/O Streams and the Standard Library 219
6.1 Different Header Files 219
6.2 C-Style String Input and Output 220
6.3 String Objects 222
6.4 A String Tokenizer 225
6.5 Operations on Characters 228
6.6 Numeric Computations 229
6.7 The I/O Stream Library 230
6.8 Stream I/O for Objects 240
6.9 I/O Manipulators 242
6.10 Summary 244
Exercises 245
SEVEN Inheritance and Class Derivation 248
7.1 Class Derivation 249
7.2 Derived Classes and Objects 252
7.3 Public Derivation 255
7.4 Derivation Principles 258
7.5 Access Control Under Class Derivation 259
7.6 Private Derivation 261
7.7 Specialization of Generic Classes 263
7.8 Type Relations Under Inheritance 265
7.9 Assignment of Objects 267
7.10 Copying of Objects 271
7.11 Derived-Object Assignment and Copying 274
7.12 Object Assignmentand Copying via Derivation 276
7.13 Multiple Inheritance 278
7.14 The I/O Stream Class Hierarchy 282
7.15 Summary 283
Exercises 284
EIGHT operator Overloading, Iterators, and
Exceptions 287
8.1 Operator Overloading 287
8.2 A Reference-Count String Class 290
8.3 Overloading [] 293
8.4 Overloading ++ and -- 294
8.5 Smart Pointers 295
8.6 Iterators 296
8.7 Nested and Local Classes 299
8.8 Robust Classes 302
8.9 User-Defined Type Conversions 303
8.10 Error and Exception Handling 306
8.11 Matrix with Exceptions 314
8.12 Managing Free Storage 316
8.13 Summary 319
Exercises 320
NINE OOP Techniques 322
9.1 Programming with Plug-Compatible Objects 322
9.2 Run-Time Type Identification 330
9.3 A Generic Tree 335
9.4 Planning Uniform Public Interfaces 343
9.5 Destruction of Plug-Compatible Objects 352
9.6 Ordering Text Lines 354
9.7 Interfaces 357
9.8 Understanding Virtual Functions 359
9.9 Inheritance Planning 361
9.10 Object-Family Classes 363
9.11 Summary 371
Exercises 372
TEN Templates 375
10.1 Basic Concepts 375
10.2 Function Templates 377
10.3 Class Templates 383
10.4 Template Compilation 388
10.5 A List Template 390
10.6 Class Template Specialization 397
10.7 Derived-Class Template 397
10.8 A Generic Hash Table 400
10.9 Generic Programming Approaches 407
10.10 Summary 409
Exercises 409
ELEVEN Standard Containers 413
11.1 The STL 413
11.2 Standard Container Headers 414
11.3 Efficiency of Sequence Containers 416
11.4 Using stack 417
11.5 Associative Containers 418
11.6 Standard Container Iterators and typedefs 421
11.7 Generic Algorithms for Containers 426
11.8 Ordered Sets 429
11.9 Standard Functors 431
11.10 For More STL Information 434
11.11 Pointers to Members 434
11.12 Instance Functions as Functors 439
11.13 Summary 439
Exercises 440
TWELVE Web CGI Programming 442
12.1 About Networking 442
12.2 Internet Basics A n.A.
12.3 The World-Wide Web 446
12.4 What IS HTML 448
12.5 Dynamic Generation of Web Pages 450
12.6 HTML Produced from C++ 452
12.7 Forms in HTML 455
12.8 HTTP Message Formats 456
12.9 Writing CGI Programs 458
12.10 Receiving Form Data 459
12.11 User Feedback Handling 461
12.12 More Information 464
12.13 Summary 465
Exercises 465
THIRTEEN Object-Oriented Design 467
13.1 Decomposition Approaches 468
13.2 Object-Oriented Design Principles 469
13.3 Design Patterns 472
13.4 The CRC Method 474
13.5 Interfacing to Existing Systems 475
13.6 Pocket Calculator Simulation 479
13.7 Summary 488
Exercises 488
FOURTEEN Compiling and Preprocessing 490
14.1 Compiling and Running C++ Programs 490
14.2 Preprocessing 492
14.3 Header Files 493
14.4 Symbolic Constants and Macros 494
14.5 Inline Functions Versus Macros 496
14.6 Conditional Text Inclusion 497
14.7 Once-Only Header Files 500
14.8 Standard Macros 500
14.9 Compilation and Execution 502
14.10 Summary 506
Exercises 507
APPENDICES
A Summary of C++ Constructs 509
B Summary of Special Member Functions 515
C C-Style Strings 516
D Unions and Bit Fields 519
E Interactive Debugging with dbx 525
F Functions with a Variable Number of Arguments 528
G Operator Precedence 531
H Implicit Type Conversions 532
I C++ Library Functions Common with C 534
J C-Style Input/output 542
K Interfacing C++ and C Programs 547
L Header Files 551
Index 552