Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 620 trang
THÔNG TIN TÀI LIỆU
Cấu trúc
Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Introduction
Chapter 1: Basic Ideas
Modern C++
C++ Program Concepts
Comments and Whitespace
Preprocessing Directives and Header Files
Functions
Statements
Data Input and Output
return Statements
Namespaces
Names and Keywords
Classes and Objects
Templates
Program Files
Standard Libraries
Code Presentation Style
Creating an Executable
Representing Numbers
Binary Numbers
Hexadecimal Numbers
Negative Binary Numbers
Octal Values
Big-Endian and Little-Endian Systems
Floating-Point Numbers
Representing Characters
ASCII Codes
UCS and Unicode
C++ Source Characters
Trigraph Sequences
Escape Sequences
Procedural and Object-Oriented Programming
Summary
Chapter 2: Introducing Fundamental Types of Data
Variables, Data, and Data Types
Defining Integer Variables
Defining Variables with Fixed Values
Integer Literals
Decimal Integer Literals
Hexadecimal Literals
Octal Literals
Binary Literals
Calculations with Integers
More on Assignment Operations
The op= Assignment Operators
using Declarations and Directives
The sizeof Operator
Incrementing and Decrementing Integers
Postfix Increment and Decrement Operations
Defining Floating-Point Variables
Floating-Point Literals
Floating-Point Calculations
Mathematical Functions
Formatting Stream Output
Mixed Expressions and Type Conversion
Explicit Type Conversion
Old-Style Casts
Finding the Limits
Working with Character Variables
Working with Unicode Characters
The auto Keyword
Lvalues and Rvalues
Summary
Chapter 3: Working with Fundamental Data Types
Operator Precedence and Associativity
Bitwise Operators
The Bitwise Shift Operators
Shifting Signed Integers
Logical Operations on Bit Patterns
Using the Bitwise AND
Using the Bitwise OR
Using the Bitwise Exclusive OR
Enumerated Data Types
Old-Style Enumerations
Synonyms for Data Types
The Lifetime of a Variable
Positioning Variable Definitions
Global Variables
Static Variables
External Variables
Summary
Chapter 4: Making Decisions
Comparing Data Values
Applying the Comparison Operators
Comparing Floating Point Values
The if Statement
Nested if Statements
Code-Neutral Character Handling
The if-else Statement
Nested if-else Statements
Understanding Nested ifs
Logical Operators
Logical AND
Logical OR
Logical Negation
The Conditional Operator
The switch Statement
Unconditional Branching
Statement Blocks and Variable Scope
Summary
Chapter 5: Arrays and Loops
Arrays
Using an Array
Understanding Loops
The for Loop
Avoiding Magic Numbers
Defining the Array Size with the Initializer List
Determining the Size of an Array
Controlling a for Loop with Floating-Point Values
More Complex for Loop Control Expressions
The Comma Operator
The Ranged-based for Loop
The while Loop
Allocating an Array at Runtime
The do-while Loop
Nested Loops
Skipping Loop Iterations
Breaking Out of a Loop
Indefinite Loops
Arrays of Characters
Multidimensional Arrays
Initializing Multidimensional Arrays
Setting Dimensions by Default
Multidimensional Character Arrays
Alternatives to Using an Array
Using array<T,N> Containers
Using std::vector<T> Containers
The Capacity and Size of a Vector
Deleting Elements from a Vector container
Summary
Chapter 6: Pointers and References
What Is a Pointer ?
The Address-Of Operator
The Indirection Operator
Why Use Pointers ?
Pointers to Type char
Arrays of Pointers
Constant Pointers and Pointers to Constants
Pointers and Arrays
Pointer Arithmetic
The Difference between Pointers
Using Pointer Notation with an Array Name
Dynamic Memory Allocation
The Stack and the Heap
Using the new and delete Operators
Dynamic Allocation of Arrays
Member Selection through a Pointer
Hazards of Dynamic Memory Allocation
Memory Leaks
Fragmentation of the Free Store
Raw Pointers and Smart Pointers
Using unique_ptr<T> Pointers
Using shared_ptr<T> Pointers
Comparing shared_ptr<T> Objects
weak_ptr<T> Pointers
Understanding References
Defining lvalue References
Using a Reference Variable in a Range-Based for Loop
Defining rvalue References
Summary
Chapter 7: Working with Strings
A Better Class of String
Defining string Objects
Operations with String Objects
Concatenating Strings
Accessing Characters in a String
Accessing Substrings
Comparing Strings
The compare( ) Function
Comparisons Using substr( )
Searching Strings
Searching for any of a Set of Characters
Searching a String Backwards
Modifying a String
Inserting a String
Replacing a Substring
Removing Characters from a String
Strings of International Characters
Strings of wchar_t Characters
Objects that contain Unicode Strings
Raw String Literals
Summary
Chapter 8: Defining Functions
Segmenting Your Programs
Functions in Classes
Characteristics of a Function
Defining Functions
The Function Body
Return Values
How the return Statement Works
Function Declarations
Function Prototypes
Passing Arguments to a Function
Pass-by-Value
Passing a Pointer to a Function
Passing an Array to a Function
const Pointer Parameters
Passing a Multidimensional Array to a Function
Pass-by-Reference
References Can Be Risky
Improving the Program
Simplifying Code using Type Aliases
References versus Pointers
Arguments to main()
Default Argument Values
Multiple Default Parameter Values
Returning Values from a Function
Returning a Pointer
Returning a Reference
Inline Functions
Static Variables
Function Overloading
Overloading and Pointer Parameters
Overloading and Reference Parameters
Overloading and const Parameters
Overloading with const Pointer Parameters
Overloading and const Reference Parameters
Overloading and Default Argument Values
A Sausage Machine for Functions
Creating Instances of a Function Template
Explicit Template Argument
Function Template Specialization
Function Templates and Overloading
Function Templates with Multiple Parameters
Non-Type Template Parameters
Trailing Return Types
Pointers to Functions
Defining Pointers to Functions
Recursion
Applying Recursion
The Quicksort Algorithm
The main() Function
The extract_words() Function
The swap() Function
The sort() function
The max_word_length() Function
The show_words() Function
Summary
Chapter 9: Lambda Expressions
Introducing Lambda Expressions
Defining a Lambda Expression
Naming a Lambda Expression
Passing a Lambda Expression to a Function
Function Templates that Accept Lambda Expression Arguments
A Function Parameter Type for Lambda Arguments
Using the std::function Template Type
The Capture Clause
Capturing Specific Variables
Using Lambda Expressions in a Template
Recursion in Lambda Expressions
Summary
Chapter 10: Program Files and Preprocessing Directives
Understanding Translation Units
The “One Definition” Rule
Program Files and Linkage
Determining Linkage for a Name
External Names
const Variables with External Linkage
Preprocessing Your Source Code
Defining Preprocessing Identifiers
Undefining an Identifier
Including Header Files
Preventing Duplication of Header File Contents
Namespaces
The Global Namespace
Defining a Namespace
Applying using Declarations
Functions and Namespaces
Unnamed Namespaces
Namespace Aliases
Nested Namespaces
Logical Preprocessing Directives
The Logical #if Directive
Testing for Specific Identifier Values
Multiple Choice Code Selection
Standard Preprocessing Macros
Debugging Methods
Integrated Debuggers
Preprocessing Directives in Debugging
Using the assert( ) Macro
Switching Off assert() Macros
Static Assertions
Summary
Chapter 11: Defining Your Own Data Types
Classes and Object-Oriented Programming
Encapsulation
Data Hiding
Inheritance
Polymorphism
Terminology
Defining a Class
Constructors
Defining Constructors Outside the Class
Default Constructor Parameter Values
Using a Constructor Initialization List
Use of the explicit Keyword
Delegating Constructors
The Copy Constructor
Implementing the Copy Constructor
Reference Parameters
Accessing Private Class Members
Friends
The Friend Functions of a Class
Friend Classes
The this Pointer
Returning this from a Function
const Objects and const Member Functions
Casting Away const
Arrays of Class Objects
The Size of a Class Object
Static Members of a Class
Static Data Members
Accessing Static Data Members
A Static Data Member of the Class Type
Static Function Members
Destructors
Pointers and References to Class Objects
Using Pointers As Class Members
Defining the Package Class
Defining the Truckload Class
Implementing the Truckload Class
Nested Classes
Summary
Chapter 12: Operator Overloading
Implementing Operators for a Class
Operator Overloading
Operators That Can Be Overloaded
Implementing an Overloaded Operator
Global Operator Functions
Implementing Full Support for an Operator
Implementing All Comparison Operators in a Class
Operator Function Idioms
Default Class Members
Defining the Destructor
When to Define a Copy Constructor
Implementing the Assignment Operator
Implementing Move Operations
Overloading the Arithmetic Operators
Improving Output Operations
Implementing One Operator in Terms of Another
Overloading the Subscript Operator
Lvalues and the Overloaded Subscript Operator
Potential Ambiguities with Conversions
Overloading Type Conversions
Overloading the Increment and Decrement Operators
Function Objects
Summary
Chapter 13: Inheritance
Classes and Object-Oriented Programming
Hierarchies
Inheritance in Classes
Inheritance vs. Aggregation
Deriving Classes
protected Members of a Class
The Access Level of Inherited Class Members
Choosing Access Specifiers in Class Hierarchies
Changing the Access Specification of Inherited Members
Constructor Operation in a Derived Class
The Copy Constructor in a Derived Class
The Default Constructor in a Derived Class
Inheriting Constructors
Destructors Under Inheritance
The Order in Which Destructors Are Called
Duplicate Data Member Names
Duplicate Function Member Names
Multiple Inheritance
Multiple Base Classes
Inherited Member Ambiguity
Repeated Inheritance
Virtual Base Classes
Converting Between Related Class Types
Summary
Chapter 14: Polymorphism
Understanding Polymorphism
Using a Base Class Pointer
Calling Inherited Functions
Virtual Functions
Requirements for Virtual Function Operation
Virtual Functions and Class Hierarchies
Using override
Using final
Access Specifiers and Virtual Functions
Default Argument Values in Virtual Functions
Virtual Function Calls with Smart Pointers
Using References to Call Virtual Functions
Calling the Base Class Version of a Virtual Function
Converting Between Pointers to Class Objects
Dynamic Casts
Casting Pointers Dynamically
Converting References
Determining the Polymorphic Type
The Cost of Polymorphism
Pure Virtual Functions
Abstract Classes
Abstract Classes As Interfaces
Indirect Abstract Base Classes
Destroying Objects Through a Pointer
Virtual Destructors
Summary
Chapter 15: Runtime Errors and Exceptions
Handling Errors
Understanding Exceptions
Throwing an Exception
The Exception Handling Process
Unhandled Exceptions
Code That Causes an Exception to Be Thrown
Nested try Blocks
How It Works
Class Objects as Exceptions
Matching a Catch Handler to an Exception
How It Works
Catching Derived Class Exceptions with a Base Class Handler
Rethrowing Exceptions
Catching All Exceptions
Functions That Throw Exceptions
Function try Blocks
Functions That Don’t Throw Exceptions
Constructor try Blocks
Exceptions and Destructors
Standard Library Exceptions
The Exception Class Definitions
Using Standard Exceptions
Deriving your own Exception Classes
Summary
Chapter 16: Class Templates
Understanding Class Templates
Defining Class Templates
Template Parameters
A Simple Class Template
Defining Function Members of a Class Template
Constructor Templates
The Destructor Template
Subscript Operator Templates
The Assignment Operator Template
Instantiating a Class Template
Static Members of a Class Template
Non-Type Class Template Parameters
Templates for Function Members with Non-Type Parameters
Arguments for Non-Type Parameters
Pointers and Arrays as Non-Type Parameters
Default Values for Template Parameters
Explicit Template Instantiation
Special Cases
Using static_assert( ) in a Class Template
Defining a Class Template Specialization
Partial Template Specialization
Choosing between Multiple Partial Specializations
Friends of Class Templates
Class Templates with Nested Classes
Function Templates for Stack Members
Summary
Chapter 17: File Input and Output
Input and Output in C++
Understanding Streams
Data Transfer Modes
Text Mode Operations
Binary Mode Operations
Advantages of Using Streams
Stream Classes
Standard Stream Objects
Stream Insertion and Extraction Operations
Stream Extraction Operations
Stream Insertion Operations
Stream Manipulators
Manipulators with Arguments
File Streams
Writing a File in Text Mode
Reading a File in Text Mode
Checking the State of a File Stream
Reading the File
Setting the Stream Open Mode
Managing the Current Stream Position
Unformatted Stream Operations
Unformatted Stream Input
Unformatted Stream Output
Errors in Stream Input/Output
Input/Output Errors and Exceptions
Stream Operations in Binary Mode
Writing Numeric Data in Binary
File Read/Write Operations
Random Access to a File
Random Access to a Binary Stream
Random File Operations in Practice
Implementing the Constructor
Checking for the Existence of a File
Finding a Prime that follows a Prime
Checking for a Prime
Implementing the Subscript Operator
Using the Primes Class
String Streams
Objects and Streams
Using the Insertion Operator with Objects
Using the Extraction Operator with Objects
Object I/O in Binary Mode
More Complex Objects in Streams
Summary
Index
Nội dung
www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them www.it-ebooks.info Contents at a Glance About the Author������������������������������������������������������������������������������������������������������������� xxiii About the Technical Reviewer������������������������������������������������������������������������������������������ xxv Introduction�������������������������������������������������������������������������������������������������������������������� xxvii ■■Chapter 1: Basic Ideas������������������������������������������������������������������������������������������������������1 ■■Chapter 2: Introducing Fundamental Types of Data �������������������������������������������������������23 ■■Chapter 3: Working with Fundamental Data Types���������������������������������������������������������55 ■■Chapter 4: Making Decisions������������������������������������������������������������������������������������������79 ■■Chapter 5: Arrays and Loops�����������������������������������������������������������������������������������������105 ■■Chapter 6: Pointers and References������������������������������������������������������������������������������151 ■■Chapter 7: Working with Strings�����������������������������������������������������������������������������������185 ■■Chapter 8: Defining Functions���������������������������������������������������������������������������������������213 ■■Chapter 9: Lambda Expressions������������������������������������������������������������������������������������271 ■■Chapter 10: Program Files and Preprocessing Directives���������������������������������������������287 ■■Chapter 11: Defining Your Own Data Types�������������������������������������������������������������������315 ■■Chapter 12: Operator Overloading���������������������������������������������������������������������������������365 ■■Chapter 13: Inheritance������������������������������������������������������������������������������������������������399 ■■Chapter 14: Polymorphism��������������������������������������������������������������������������������������������429 v www.it-ebooks.info ■ Contents at a Glance ■■Chapter 15: Runtime Errors and Exceptions�����������������������������������������������������������������463 ■■Chapter 16: Class Templates�����������������������������������������������������������������������������������������495 ■■Chapter 17: File Input and Output���������������������������������������������������������������������������������533 Index���������������������������������������������������������������������������������������������������������������������������������593 vi www.it-ebooks.info Introduction Welcome to BeginningC++ This is a revised and updated version of my previous book, Beginning ANSI C++ The C++ language has been extended and improved considerably since the previous book, so much so that it was no longer possible to squeeze detailed explanations of all of C++ in a single book This tutorial will teach enough of the essential C++ language and Standard Library features to enable you to write your own C++ applications With the knowledge from this book you should have no difficulty in extending the depth and scope of your C++ expertise C++ is much more accessible than many people assume I have assumed no prior programming knowledge If you are keen to learn and have an aptitude for thinking logically, getting a grip on C++ will be easier than you might imagine By developing C++ skills, you’ll be learning a language that is already used by millions, and that provides the capability for application development in just about any context The C++ language in this book corresponds to the latest ISO standard, commonly referred to as C++ 14 C++ 14 is a minor extension over the previous standard, C++ 11, so there is very little in the book that is C++ 14 specific All the examples in the book can be compiled and executed using C++ 11-conforming compilers that are available now Using the Book To learn C++ with this book, you’ll need a compiler that conforms reasonably well to the C++ 11 standard and a text editor suitable for working with program code There are several compilers available currently that are reasonably C++ 11 compliant, some of which are free The GCC compiler that is produced by the GNU Project has comprehensive support for C++ 11 and it is open source and free to download Installing GCC and putting it together with a suitable editor can be a little tricky if you are new to this kind of thing An easy way to install GCC along with a suitable editor is to download Code::Blocks from http://www.codeblocks.org Code::Blocks is a free IDE for Linux, Apple Mac OS X, and Microsoft Windows It supports program development using several compilers including compilers for GCC, Clang, and open Watcom This implies you get support for C, C++, and Fortran Another possibility is to use Microsoft Visual C++ that runs under Microsoft Windows It is not fully compliant with C++ 11, but it’s getting there The free version is available as Microsoft Visual Studio 2013 Express and at the time of writing this will compile most of the examples, and should compile them all eventually You can download it from http://www.microsoft.com/en-us/download/details.aspx?id=43733 While the Microsoft Visual C++ compiler is more limited than GCC, in terms of the extent to which C++ 11 is supported, you get a professional editor and support for other languages such as C# and Basic Of course, you can always install both! There are other compilers that support C++ 11, which you can find with a quick online search I’ve organized the material in this book to be read sequentially, so you should start at the beginning and keep going until you reach the end However, no one ever learned programming by just reading a book You’ll only learn how to program in C++ by writing code, so make sure you key in all the examples—don’t just copy them from the download files—and compile and execute the code that you’ve keyed in This might seem tedious at times, but it’s surprising how much just typing in C++ statements will help your understanding, especially when you may feel you’re struggling with some of the ideas If an example doesn’t work, resist the temptation to go straight back to the book to see why Try to figure out from your code what is wrong This is good practice for what you’ll have to when you are developing C++ applications for real xxvii www.it-ebooks.info ■ Introduction Making mistakes is a fundamental part of the learning process and the exercises should provide you with ample opportunity for that It’s a good idea to dream up a few exercises of your own If you are not sure about how to something, just have a go before looking it up The more mistakes you make, the greater the insight you’ll have into what can, and does, go wrong Make sure you attempt all the exercises, and remember, don’t look at the solutions until you’re sure that you can’t work it out yourself Most of these exercises just involve a direct application of what’s covered in a chapter—they’re just practice, in other words—but some also require a bit of thought or maybe even inspiration I wish you every success with C++ Above all, enjoy it! —Ivor Horton xxviii www.it-ebooks.info Chapter Basic Ideas I’ll sometimes have to make use of things in examples before I have explained them in detail This chapter is intended to help when this occurs by giving you an overview of the major elements of C++ and how they hang together I’ll also explain a few concepts relating to the representation of numbers and characters in your computer In this chapter you’ll learn: • What is meant by Modern C++ • The elements of a C++ program • How to document your program code • How your C++ code becomes an executable program • How object-oriented programming differs from procedural programming • What binary, hexadecimal, and octal number systems are • What Unicode is Modern C++ Modern C++ is programming using of the features of the latest and greatest incarnation of C++ This is the C++ language defined by the C++ 11 standard, which is being modestly extended and improved by the latest standard, C++ 14 This book relates to C++ as defined by C++14 There’s no doubt that C++ is the most widely used and most powerful programming language in the world today If you were just going to learn one programing language, C++ is the ideal choice It is effective for developing applications across an enormous range of computing devices and environments: for personal computers, workstations, mainframe computers, tablets, and mobile phones Just about any kind of program can be written in C++ from device drivers to operating systems, from payroll and administrative programs to games C++ compilers are available widely too There are up-to-date compilers that run on PCs, workstations, and mainframes, often with cross-compiling capabilities, where you can develop the code in one environment and compile it to execute in another C++ comes with a very extensive Standard Library This is a huge collection of routines and definitions that provide functionality that is required by many programs Examples are numerical calculations, string processing, sorting and searching, organizing and managing data, and input and output The Standard Library is so vast that we will only scratch the surface of what is available in this book It really needs several books to fully elaborate all the capability it provides Beginning STL is a companion book that is a tutorial on using the Standard Template Library, which is the subset of the C++ Standard Library for managing and processing data in various ways www.it-ebooks.info Chapter ■ Basic Ideas Given the scope of the language and the extent of the library, it’s not unusual for a beginner to find C++ somewhat daunting It is too extensive to learn in its entirety from a single book However, you don’t need to learn all of C++ to be able to write substantial programs You can approach the language step by step, in which case it really isn’t difficult An analogy might be learning to drive a car You can certainly become a very competent and safe driver without necessarily having the expertise, knowledge, and experience to drive in the Indianapolis 500 With this book you can learn everything you need to program effectively in C++ By the time you reach the end, you’ll be confidently writing your own applications You’ll also be well equipped to explore the full extent of C++ and its Standard Library C++ Program Concepts There will be much more detail on everything I discuss in this section later in the book I’ll jump straight in with the complete, fully working, C++ program shown in Figure 1-1, which explains what the various bits of it are I’ll use the example as a base for discussing some more general aspects of C++ This is a statement Statements end with a semicolon There is also a comment on this line // Ex1_01.cpp // A complete C++ program These two lines are comments Comments begin with // #include This line adds input/output capability int main ( ) { This is the first line of the function main int answer {42}; // Defines answer with value 42 std::cout