Statistics
23
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-21
Support
Share

AuthorKyle Loudon

C++ is a complex language with many subtle facets. This is especially true when it comes to object-oriented and template programming. The C++ Pocket Reference is a memory aid for C++ programmers, enabling them to quickly look up usage and syntax for unfamiliar and infrequently used aspects of the language. The book's small size makes it easy to carry about, ensuring that it will always be at-hand when needed. Programmers will also appreciate the book's brevity; as much information as possible has been crammed into its small pages.

Tags
c/c++
ISBN: 0596004966
Publisher: O'Reilly Media
Publish Year: 2006
Language: 英文
Pages: 140
File Format: PDF
File Size: 1.3 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

www.it-ebooks.info
www.it-ebooks.info
C++ Pocket Reference Kyle Loudon Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo ,TITLE.13859 Page 3 Monday, June 19, 2006 7:03 PM www.it-ebooks.info
C++ Pocket Reference by Kyle Loudon Copyright © 2003 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly Media, Inc. books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Jonathan Gennick Production Editor: Emily Quill Cover Designer: Ellie Volckhausen Interior Designer: David Futato Printing History: May 2003: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Pocket Reference series designations, C++ Pocket Reference, the image of a chipmunk, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. 0-596-00496-6 [C] [6/06] COPYRIGHT Page iv Friday, June 2, 2006 2:31 PM www.it-ebooks.info
v Contents Introduction 1 Typographic Conventions 2 Acknowledgments 2 Compatibility with C 2 Program Structure 3 Startup 3 Termination 5 Header Files 5 Source Files 7 Preprocessor Directives 8 Preprocessor Macros 11 Fundamental Types 12 bool 12 char and wchar_t 13 short, int, long 15 float, double, long double 16 Compound Types 17 Enumerations 18 Arrays 19 Strings 22 Pointers 24 Pointers to Members 26 www.it-ebooks.info
vi | Contents References 27 Class Types 28 Type Conversions and Definitions 28 Type Conversions 28 Type Definitions 31 Lexical Elements 31 Comments 32 Identifiers 32 Reserved Words 33 Literals 34 Operators 34 Expressions 46 Scope 47 Local Scope 47 Class Scope 47 Namespace Scope 48 File Scope 48 Other Scopes 49 Enclosing Scopes 49 Declarations 50 Declaring Variables 51 Declaring Functions 52 Storage Classes 55 Qualifiers 57 Statements 59 Expression Statements 59 Null Statements 59 Compound Statements 59 Iteration Statements 60 www.it-ebooks.info
Contents | vii Selection Statements 62 Jump Statements 64 Namespaces 66 using Declarations 67 using Directives 67 Unnamed Namespaces 68 Classes, Structs, and Unions 68 Declaring Objects 69 Accessing Members 69 Declaring Data Members 70 Declaring Member Functions 74 Access Levels for Members 78 Friends 79 Constructors 80 Destructors 83 Nested Declarations 85 Forward Declarations 86 Structs 86 Unions 86 Inheritance 88 Constructors and Inheritance 89 Destructors and Inheritance 90 Virtual Member Functions 91 Abstract Base Classes 94 Access Levels for Inheritance 94 Multiple Inheritance 95 Virtual Base Classes 97 Templates 98 Template Classes 98 Template Functions 101 www.it-ebooks.info
viii | Contents Overloading 104 Overloading Functions 104 Overloading Operators 105 Memory Management 108 Memory Allocation 108 Memory Reclamation 110 Casts and Runtime Type Information 112 C-Style Casts 112 Casts in C++ 112 Runtime Type Information 115 Exception Handling 117 try 117 throw 117 catch 118 Exception Specifications 119 The C++ Standard Library 120 The std Namespace 121 C Standard Library Support 121 C++ Standard Header Files 122 I/O Streams 122 www.it-ebooks.info
1 Chapter 1 C++ Pocket Reference Introduction The C++ Pocket Reference is a quick reference to the C++ programming language as defined by the international stan- dard INCITS/ISO/IEC 14882–1998. It consists of a number of short sections, each further divided into specific topics. Many of the topics include pointed, canonical examples. At the outset, it is important to recognize that C++ is a vast language, admittedly difficult to describe in a pocket refer- ence. As a result, this reference is devoted almost exclusively to presenting the language itself. Other references are avail- able from O’Reilly & Associates describing the C++ Stan- dard Library, a vast subject on its own. The C++ Standard Library includes all of the facilities of the C Standard Library plus many new ones, such as the Standard Template Library (STL) and I/O streams. This book has been written for developers with a variety of backgrounds and experience levels in C++. Those with expe- rience using C++ will find this book to be a uniquely focused reference to its most commonly used features. If you are new to C++, you may wish to work with a tutorial first and return to this reference later to research specific topics. www.it-ebooks.info
2 | C++ Pocket Reference Typographic Conventions This book uses the following typographic conventions: Italic This style is used for filenames and for items emphasized in the text. Constant width This style is used for code, commands, keywords, and names for types, variables, functions, and classes. Constant width italic This style is used for items that you need to replace. Acknowledgments I would like to thank Jonathan Gennick, my editor at O’Reilly, for his support and direction with this book. Thanks also to Uwe Schnitker, Danny Kalev, and Ron Passe- rini for taking the time to read and comment on an early draft of this book. Compatibility with C With some minor exceptions, C++ was developed as an extension, or superset, of C. This means that well-written C programs generally will compile and run as C++ programs. (Most incompatibilities stem from the stricter type checking that C++ provides.) So, C++ programs tend to look syntacti- cally similar to C and use much of C’s original functionality. This being said, don’t let the similarities between C and C++ fool you into thinking that C++ is merely a trivial derivation of C. In fact, it is a rich language that extends C with some grand additions. These include support for object-oriented programming, generic programming using templates, namespaces, inline functions, operator and function over- loading, better facilities for memory management, refer- ences, safer forms of casting, runtime type information, exception handling, and an extended standard library. www.it-ebooks.info
Program Structure | 3 Program Structure At the highest level, a C++ program is composed of one or more source files that contain C++ source code. Together, these files define exactly one starting point, and perhaps vari- ous points at which to end. C++ source files frequently import, or include, additional source code from header files. The C++ preprocessor is responsible for including code from these files before each file is compiled. At the same time, the preprocessor can also perform various other operations through the use of prepro- cessor directives. A source file after preprocessing has been completed is called a translation unit. Startup The function main is the designated start of a C++ program, which you as the developer must define. In its standard form, this function accepts zero or two arguments supplied by the operating system when the program starts, although many C++ implementations allow additional parameters. Its return type is int. For example: int main( ) int main(int argc, char *argv[]) argc is the number of arguments specified on the command line; argv is an array of null-terminated (C-style) strings con- taining the arguments in the order they appear. The name of the executable is stored in argv[0], and may or may not be prefixed by its path. The value of argv[argc] is 0. The following shows the main function for a simple C++ pro- gram that prompts the user for actions to perform on an account: #include <iostream> #include <cmath> #include <cstdlib> using namespace std; www.it-ebooks.info
4 | C++ Pocket Reference #include "Account.h" int main(int argc, char *argv[]) { Account account(0.0); char action; double amount; if (argc > 1) account.deposit(atof(argv[1])); while (true) { cout << "Balance is " << account.getBalance( ) << endl; cout << "Enter d, w, or q: "; cin >> action; switch (action) { case 'd': cout << "Enter deposit: "; cin >> amount; account.deposit(amount); break; case 'w': cout << "Enter withdrawal: "; cin >> amount; account.withdraw(amount); break; case 'q': exit(0); default: cout << "Bad command" << endl; } } return 0; } www.it-ebooks.info
Program Structure | 5 The class for the account is defined in a later example. An initial deposit is made into the account using an amount specified on the command line when the program is started. The function atof (from the C++ Standard Library) is used to convert the command-line argument from a string to a double. Termination A C++ program terminates when you return from main. The value you return is passed back to the operating system and becomes the return value for the executable. If no return is present in main, an implicit return of 0 takes places after fall- ing through the body of main. You can also terminate a pro- gram by calling the exit function (from the C++ Standard Library), which accepts the return value for the executable as an argument. Header Files Header files contain source code to be included in multiple files. They usually have a .h extension. Anything to be included in multiple places belongs in a header file. A header file should never contain the following: • Definitions for variables and static data members (see “Declarations” for the difference between declarations and definitions). • Definitions for functions, except those defined as tem- plate functions or inline functions. • Namespaces that are unnamed. NOTE Header files in the C++ Standard Library do not use the .h extension; they have no extension. www.it-ebooks.info
6 | C++ Pocket Reference Often you create one header file for each major class that you define. For example, Account is defined in the header file Account.h, shown below. Of course, header files are used for other purposes, and not all class definitions need to be in header files (e.g., helper classes are defined simply within the source file in which they will be used). #ifndef ACCOUNT_H #define ACCOUNT_H class Account { public: Account(double b); void deposit(double amt); void withdraw(double amt); double getBalance( ) const; private: double balance; }; #endif The implementation of this class is in Account.cpp. You use the preprocessor directive #include to include a header file within another file (see “Preprocessor Directives”). Because header files are often included by other headers themselves, care must be taken not to include the same file more than once, which can lead to compilation errors. To avoid this, it is conventional to wrap the contents of header files with the preprocessor directives #ifndef, #define, and #endif, as done in the previous example. The tactic of wrapping a header file forces the preprocessor to test an identifier. If that identifier is not defined, the pre- processor defines it and processes the file’s contents. As an example, the contents of Account.h are processed only when ACCOUNT_H is undefined, and the first thing that processing does is to define ACCOUNT_H to ensure the header is not www.it-ebooks.info
Program Structure | 7 processed a second time. To ensure uniqueness, X_H is typi- cally used as the identifier, where X is the name of the header file without its extension. Source Files C++ source files contain C++ source code. They usually have a .cpp extension. During compilation, the compiler typi- cally translates source files into object files, which often have a .obj or .o extension. Object files are joined by the linker to produce a final executable or library. Often you create one source file for each major class you implement. For example, the implementation of Account is in Account.cpp, shown below. Of course, there is no require- ment about this; source files often contain more than just the implementation of a single class. #include "Account.h" Account::Account(double b) { balance = b; } void Account::deposit(double amt) { balance += amt; } void Account::withdraw(double amt) { balance -= amt; } double Account::getBalance( ) const { return balance; } www.it-ebooks.info
8 | C++ Pocket Reference Preprocessor Directives The C++ preprocessor can be used to perform a number of useful operations controlled via several directives. Each direc- tive begins with a pound sign (#) as the first character that is not whitespace on a line. Directives can span multiple lines by including a backslash (\) at the end of intermediate lines. #define The #define directive replaces an identifier with the text that follows it wherever the identifier occurs in a source file. For example: #define BUFFER_SIZE 80 char buffer[BUFFER_SIZE]; If you specify no text after the identifier, the preprocessor simply defines the identifier so that any check for its defini- tion tests true and it expands to nothing in the source code. (You can see this in use earlier where ACCOUNT_H was defined.) NOTE In C++, it is preferable to use enumerations, and to a lesser degree, variables and data members declared using the keywords const or static const for constant data, rather than the #define directive. The #define directive can accept arguments for macro substi- tution in the text. For example: #define MIN(a, b) (((a) < (b)) ? (a):(b)) int x = 5, y = 10, z; z = MIN(x, y); // This sets z to 5. In order to avoid unexpected problems with operator prece- dence, parameters should be fully parenthesized in the text, as shown above. www.it-ebooks.info
Program Structure | 9 NOTE In C++, it is preferable to use templates and inline func- tions in place of macros. Templates and inline functions eliminate unexpected results produced by macros, such as MIN(x++, y) incrementing x twice when a is less than b. (Macro substitution treats x++, not the result of x++, as the first parameter.) #undef The #undef directive undefines an identifier so that a check for its definition tests false. For example: #undef LOGGING_ENABLED #ifdef, #ifndef, #else, #endif You use the #ifdef, #ifndef, #else, and #endif directives together. The #ifdef directive causes the preprocessor to include different code based on whether or not an identifier is defined. For example: #ifdef LOGGING_ENABLED cout << "Logging is enabled" << endl; #else cout << "Logging is disabled" << endl; #endif Using #else is optional. #ifndef works similarly but includes the code following the #ifndef directive only if the identifier is not defined. #if, #elif, #else, #endif The #if, #elif, #else, and #endif directives, like the direc- tives of #ifdef, are used together. These cause the preproces- sor to include or exclude code based on whether an expression is true. For example: #if (LOGGING_LEVEL == LOGGING_MIN && \ LOGGING_FLAG) cout << "Logging is minimal" << endl; www.it-ebooks.info
10 | C++ Pocket Reference #elif (LOGGING_LEVEL == LOGGING_MAX && \ LOGGING_FLAG) cout << "Logging is maximum" << endl; #elif LOGGING_FLAG cout << "Logging is standard" << endl; #endif The #elif (else-if) directive is used to chain a series of tests together, as shown above. #include The #include directive causes the preprocessor to include another file, usually a header file. You enclose standard header files with angle brackets, and user-defined header files with quotes. For example: #include <iostream> #include "Account.h" The preprocessor searches different paths depending on the form of enclosure. The paths searched depend on the system. #error The #error directive causes compilation to stop and a speci- fied string to be displayed. For example: #ifdef LOGGING_ENABLED #error Logging should not be enabled #endif #line The #line directive causes the preprocessor to change the current line number stored internally by the compiler during compilation in the macro _ _LINE_ _. For example: #line 100 A filename optionally can be specified in double quotes after the line number. This changes the name of the file stored internally by the compiler in the macro _ _FILE_ _. For example: #line 100 "NewName.cpp" www.it-ebooks.info
Program Structure | 11 #pragma Some operations that the preprocessor can perform are implementation-specific. The #pragma directive allows you to control these operations by specifying the directive along with any parameters in a form that the directive requires. For example: #ifdef LOGGING_ENABLED #pragma message("Logging enabled") #endif Under Microsoft Visual C++ 6.0, the message directive informs the preprocessor to display a message during compi- lation at the point where this line is encountered. The direc- tive requires one parameter: the message to display. This is enclosed in parentheses and quoted. Preprocessor Macros The C++ preprocessor defines several macros for insert- ing information into a source file during compilation. Each macro begins and ends with two underscores, except for _ _cplusplus, which has no terminating underscores. _ _LINE_ _ Expands to the current line number of the source file being compiled. _ _FILE_ _ Expands to the name of the source file being compiled. _ _DATE_ _ Expands to the date on which the compilation is taking place. _ _TIME_ _ Expands to the time at which the compilation is taking place. _ _TIMESTAMP_ _ Expands to the date and time at which the compilation is taking place. www.it-ebooks.info
12 | C++ Pocket Reference _ _STDC_ _ Will be defined if the compiler is in full compliance with the ANSI C standard. _ _cplusplus Will be defined if the program being compiled is a C++ program. How a compiler determines whether a given program is a C++ program is compiler-specific. You may need to set a compiler option, or your compiler may look at the source file’s extension. Fundamental Types The type for an identifier determines what you are allowed to do with it. You associate a type with an identifier when you declare it. When declaring an identifier, you also may have the opportunity to specify a storage class and one or more qualifiers (see “Declarations”). The fundamental types of C++ are its Boolean, character, integer, floating-point, and void types. The Boolean, charac- ter, and integer types of C++ are called integral types. Inte- gral and floating-point types are collectively called arithmetic types. bool Booleans are of type bool. The bool type is used for values of truth. For example: bool flag; ... if (flag) { // Do something when the flag is true. } Boolean values Booleans have only two possible values: true or false. The typical size of a bool is one byte. www.it-ebooks.info
The above is a preview of the first 20 pages. Register to read the complete e-book.