Tải bản đầy đủ (.pdf) (138 trang)

Kyle loudon c++ pocket reference 2003

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.3 MB, 138 trang )

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

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
Fundamental Types
|
13
Boolean literals

The only Boolean literals are the C++ keywords true and
false. By convention, false is defined as 0; any other value is
considered true.
char and wchar_t
Characters are of type char or wchar_t. The char type is used
for integers that refer to characters in a character set (usually
ASCII). For example:
char c = 'a';
cout << "Letter a: " << c << endl;
The wchar_t type is a distinct type large enough to represent
the character sets of all locales supported by the implementa-
tion. To use facilities related to the
wchar_t type, you include
the standard header file <cwchar>.
Character types may be specified either as
signed or unsigned
and are sometimes used simply to store small integers. For
example:
signed char small = -128;
unsigned char flags = 0x7f;
A signed char represents both positive and negative values,
typically by sacrificing one bit to store a sign. An
unsigned
char
doesn’t have a sign and therefore can hold larger posi-
tive values, typically twice as large. If neither
signed nor
unsigned is specified, characters are usually signed by default,
but this is left up to the compiler.
Character values

The range of values that characters may represent is found in
the standard header file <climits>. The size of a
char is one
byte. The size of a byte technically is implementation-
defined, but it is rarely anything but eight bits. The size of
www.it-ebooks.info
14
|
C++ Pocket Reference
the wchar_t type is also implementation-defined, but is typi-
cally two bytes.
Character literals
Character literals are enclosed by single quotes. For example:
char c = 'A';
To specify literals for wide characters, you use the prefix L.
For example:
wchar_t c = L'A';
To allow special characters, such as newlines and single
quotes, to be used within literals, C++ defines a number of
escape sequences, each of which begins with a backslash.
Table 1 presents these escape sequences. There is no limit to
the number of hexadecimal digits that can appear after
\x in
a hexadecimal escape sequence. Octal escape sequences can
be at most three digits.
Table 1. Character escape sequences
Escape sequence Description
\a Alert (system bell)
\b Backspace
\f Form feed

\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quote
\" Double quote
\? Question mark
\ooo Octal number ooo
\xhhh Hexadecimal number hhh
www.it-ebooks.info
Fundamental Types
|
15
short, int, long
Integers are of type short, int,orlong. These types differ in
size and the range of values they can represent. For example:
short sval = 32767;
int ival = 2147483647;
long lval = 0x7fffffff;
Integers may be specified as either signed or unsigned. For
example:
signed short total;
unsigned short flags = 0xf0f0;
Signed integers represent both positive and negative values,
typically by sacrificing one bit to store a sign. Unsigned inte-
gers don’t have a sign and therefore can hold larger positive
values. If an integer is not specified as either
signed or
unsigned, it is signed by default.

Integer values
The range of values that each of the integer types may repre-
sent is found in the standard header file <climits>. The exact
size of a
short, int,orlong is left up to the compiler, but is
typically two, four, or four bytes respectively. Although the
size of each type can vary, the compiler guarantees that the
size of a
short is less than or equal to the size of an int, and
the size of an
int is less than or equal to the size of a long.
Integer literals
Literals for integers have several forms, as shown in Table 2.
If
U, u, L,orl is not used as a suffix, the compiler assigns a
type appropriate for the magnitude of the literal.
www.it-ebooks.info
16
|
C++ Pocket Reference
float, double, long double
Floating points are of type float, double,orlong double.
These types differ in size and in the range and precision of
values they can represent. For example:
float fval = 3.4e+38F;
double dval = 1.7e+308;
Floating-point values
The range and precision of values that each of the floating-
point types may represent is found in the standard header file
<cfloat>. The exact size, range, and precision of a

float,
double,orlong double is left up to the compiler, but is typi-
cally four, eight, or ten bytes respectively. Although the size
of each type can vary, the compiler guarantees that the size of
a
float is less than or equal to the size of a double, and the
size of a double is less than or equal to the size of a
long
double
.
Floating-point literals
Literals for floating points can take on several forms, as
shown in Table 3. If
F, f, L,orl is not used as a suffix, the
compiler assigns a type of
double.
Table 2. Integer literals
Examples Description
12
-5
The most common form of integer literals.
012
0377
Literals that begin with 0 are octal values (e.g., 012 is the octal literal
for the decimal number 10).
0x2a
0xffff
Literals that begin with 0x are hexadecimal values (e.g., 0x2a is the
hexadecimal literal for the decimal number 42).
256L

0x7fL
Literals with L (or l) in the suffix are treated as long.
0x80U
0xffffUL
Literals with U (or u) in the suffix are treated as unsigned.
www.it-ebooks.info
Compound Types
|
17
void
The void type indicates the absence of a value. One use is in
declaring functions that do not return a value. For example:
void sayHello( )
{
cout << "Hello" << endl;
}
Another use is in declaring a pointer that can point to any
type of data. For example:
int i = 200;
void *p = &i;
The variable p points to an int. Variables that are not point-
ers cannot be declared as
void.
Compound Types
Arithmetic types are the building blocks for more complex
types, called compound types. These include enumerations,
arrays, strings, pointers, pointers to members, references,
and the various class types of C++, as well as functions.
Arithmetic types, enumerations, pointers, and pointers to
members are collectively called scalar types.

Table 3. Floating-point literals
Examples Description
1.2345
-57.0
0.4567
The most common form of literal floating points.
1.992e+2
1.71e-25
Literals expressed in scientific notation.
8.00275F
3.4e+38L
Literals with the suffix F (or f) are given the type float; literals
with the suffix L (or l) are given the type long double.
www.it-ebooks.info

×