Beginning C++17 (eBook)
XXVIII, 771 Seiten
Apress (Verlag)
978-1-4842-3366-5 (ISBN)
- Define variables and make decisions
- Work with arrays and loops, pointers and references, strings, and more
- Write your own functions, types, and operators
- Discover the essentials of object-oriented programming
- Use overloading, inheritance, virtual functions and polymorphism
- Write generic function templates and class templates
- Get up to date with modern C++ features: auto type declarations, move semantics, lambda expressions, and more
- Examine the new additions to C++17
Ivor Horton is self-employed in consultancy and writes programming tutorials. He is the author of many programming books. Ivor worked for IBM for many years and holds a bachelor's degree, with honors, in mathematics. Horton's experience at IBM includes programming in most languages (like assembler and high-level languages on a variety of machines), real-time programming, and designing and implementing real-time closed loop industrial control systems. He has extensive experience teaching programming to engineers and scientists (Fortran, PL/1, APL, etc.). Horton is an expert in mechanical, process, and electronic CAD systems; mechanical CAM systems; and DNC/CNC systems.
Learn how to program using the updated C++17 language. You'll start with the basics and progress through step-by-step examples to become a working C++ programmer. All you need are Beginning C++17 and any recent C++ compiler and you'll soon be writing real C++ programs. There is no assumption of prior programming knowledge.All language concepts that are explained in the book are illustrated with working program examples, and all chapters include exercises for you to test and practice your knowledge. Code downloads are provided for all examples from the text and solutions to the exercises.This latest edition has been fully updated to the latest version of the language, C++17, and to all conventions and best practices of so-called modern C++. Beginning C++17 also introduces the elements of the C++ Standard Library that provide essential support for the C++17 language. What You'll LearnDefine variables and make decisionsWork with arrays and loops, pointers and references, strings, and moreWrite your own functions, types, and operatorsDiscover the essentials of object-oriented programmingUse overloading, inheritance, virtual functions and polymorphismWrite generic function templates and class templates Get up to date with modern C++ features: auto type declarations, move semantics, lambda expressions, and moreExamine the new additions to C++17Who This Book Is ForProgrammers new to C++ and those who may be looking for a refresh primer on the C++17 programming language in general.
Ivor Horton is self-employed in consultancy and writes programming tutorials. He is the author of many programming books. Ivor worked for IBM for many years and holds a bachelor's degree, with honors, in mathematics. Horton's experience at IBM includes programming in most languages (like assembler and high-level languages on a variety of machines), real-time programming, and designing and implementing real-time closed loop industrial control systems. He has extensive experience teaching programming to engineers and scientists (Fortran, PL/1, APL, etc.). Horton is an expert in mechanical, process, and electronic CAD systems; mechanical CAM systems; and DNC/CNC systems.Peter Van Weert is a Belgian software engineer whose main interests and expertise are application software development, programming languages, algorithms, and data structures. He received his master of science degree in computer science summa cum laude with congratulations of the Board of Examiners from the University of Leuven. In 2010, he completed his PhD thesis there on the design and efficient compilation of rule-based programming languages at the research group for declarative programming languages and artificial intelligence. During his doctoral studies, he was a teaching assistant for object-oriented programming (Java), software analysis and design, and declarative programming. After graduating, Peter worked at Nikon Metrology for more than six years on large-scale, industrial application software in the area of 3D laser scanning and point cloud inspection. He learned to master C++ and refactoring and debugging of very large code bases, and he gained further proficiency in all aspects of the software development process, including the analysis of functional and technical requirements, and agile and scrum-based project and team management. Today, Peter works for Danaher in its R&D unit for digital dentistry software, developing software for the dental practice of tomorrow. In his spare time, he has co-authored two books on C++ and two award-winning Windows 8 apps and is a regular expert speaker at, and board member of, the Belgian C++ Users Group.
Contents 5
About the Authors 22
About the Technical Reviewer 23
Introduction 24
Chapter 1: Basic Ideas 26
Modern C++ 26
Standard Libraries 27
C++ Program Concepts 28
Source Files and Header Files 28
Comments and Whitespace 29
Preprocessing Directives and Standard Library Headers 29
Functions 30
Statements 30
Data Input and Output 31
return Statements 32
Namespaces 32
Names and Keywords 33
Classes and Objects 34
Templates 34
Code Appearance and Programming Style 34
Creating an Executable 35
Procedural and Object-Oriented Programming 37
Representing Numbers 38
Binary Numbers 38
Hexadecimal Numbers 39
Negative Binary Numbers 41
Octal Values 42
Bi-Endian and Little-Endian Systems 43
Floating-Point Numbers 44
Representing Characters 45
ASCII Codes 46
UCS and Unicode 46
C++ Source Characters 47
Escape Sequences 47
Summary 49
Chapter 2: Introducing Fundamental Types of Data 51
Variables, Data, and Data Types 51
Defining Integer Variables 52
Signed Integer Types 54
Unsigned Integer Types 55
Zero Initialization 56
Defining Variables with Fixed Values 56
Integer Literals 57
Decimal Integer Literals 57
Hexadecimal Literals 58
Octal Literals 58
Binary Literals 59
Calculations with Integers 59
Compound Arithmetic Expressions 60
Assignment Operations 61
The op= Assignment Operators 64
The sizeof Operator 66
Incrementing and Decrementing Integers 66
Postfix Increment and Decrement Operations 67
Defining Floating-Point Variables 68
Floating-Point Literals 69
Floating-Point Calculations 70
Pitfalls 70
Invalid Floating-Point Results 71
Mathematical Functions 72
Formatting Stream Output 75
Mixed Expressions and Type Conversion 77
Explicit Type Conversion 78
Old-Style Casts 80
Finding the Limits 81
Finding Other Properties of Fundamental Types 82
Working with Character Variables 83
Working with Unicode Characters 84
The auto Keyword 85
Summary 86
Chapter 3: Working with Fundamental Data Types 89
Operator Precedence and Associativity 89
Bitwise Operators 91
The Bitwise Shift Operators 92
Shifting Signed Integers 94
Logical Operations on Bit Patterns 95
Using the Bitwise AND 95
Using the Bitwise OR 96
Using the Bitwise Complement Operator 97
Using the Bitwise Exclusive OR 98
Using the Bitwise Operators: An Example 99
Enumerated Data Types 101
Aliases for Data Types 104
The Lifetime of a Variable 105
Global Variables 106
Summary 109
Chapter 4: Making Decisions 112
Comparing Data Values 112
Applying the Comparison Operators 113
Comparing Floating-Point Values 115
The if Statement 115
Nested if Statements 119
Character Classification and Conversion 120
The if-else Statement 122
Nested if-else Statements 124
Understanding Nested ifs 125
Logical Operators 126
Logical AND 127
Logical OR 127
Logical Negation 128
Combining Logical Operators 128
Logical Operators on Integer Operands 130
Logical Operators vs. Bitwise Operators 131
Short-Circuit Evaluation 131
Logical XOR 132
The Conditional Operator 133
The switch Statement 135
Fallthrough 139
Statement Blocks and Variable Scope 141
Initialization Statements 142
Summary 143
Chapter 5: Arrays and Loops 146
Arrays 146
Using an Array 146
Understanding Loops 148
The for Loop 149
Avoiding Magic Numbers 151
Defining the Array Size with the Braced Initializer 153
Determining the Size of an Array 153
Controlling a for Loop with Floating-Point Values 155
More Complex for Loop Control Expressions 158
The Comma Operator 159
The Range-Based for Loop 160
The while Loop 161
The do-while Loop 163
Nested Loops 165
Skipping Loop Iterations 168
Breaking Out of a Loop 169
Indefinite Loops 169
Controlling a for Loop with Unsigned Integers 173
Arrays of Characters 175
Multidimensional Arrays 178
Initializing Multidimensional Arrays 181
Setting Dimensions by Default 182
Multidimensional Character Arrays 183
Allocating an Array at Runtime 184
Alternatives to Using an Array 187
Using array< T,N>
Accessing Individual Elements 188
Operations on array< >
Conclusion and Example 190
Using std::vector< T>
Deleting Elements 195
Example and Conclusion 195
Summary 197
Chapter 6: Pointers and References 200
What Is a Pointer? 200
The Address-Of Operator 203
The Indirection Operator 204
Why Use Pointers? 206
Pointers to Type char 206
Arrays of Pointers 209
Constant Pointers and Pointers to Constants 211
Pointers and Arrays 213
Pointer Arithmetic 214
The Difference Between Pointers 215
Comparing Pointers 216
Using Pointer Notation with an Array Name 216
Dynamic Memory Allocation 219
The Stack and the Free Store 219
Using the new and delete Operators 220
Dynamic Allocation of Arrays 222
Multidimensional Arrays 224
Member Selection Through a Pointer 226
Hazards of Dynamic Memory Allocation 226
Dangling Pointers and Multiple Deallocations 227
Allocation/Deallocation Mismatch 227
Memory Leaks 227
Fragmentation of the Free Store 228
Golden Rule of Dynamic Memory Allocation 229
Raw Pointers and Smart Pointers 229
Using unique_ptr< T>
Using shared_ptr< T>
Understanding References 237
Defining References 237
Using a Reference Variable in a Range-Based for Loop 239
Summary 240
Chapter 7: Working with Strings 242
A Better Class of String 242
Defining string Objects 243
Operations with String Objects 246
Concatenating Strings 247
Concatenating Strings and Characters 249
Concatenating Strings and Numbers 250
Accessing Characters in a String 251
Accessing Substrings 253
Comparing Strings 253
The compare() Function 256
Comparisons Using substr() 259
Searching Strings 260
Searching Within Substrings 261
Searching for Any of a Set of Characters 263
Searching a String Backward 265
Modifying a String 266
Inserting a String 267
Replacing a Substring 268
Removing Characters from a String 270
std::string vs. std::vector< char>
Converting Strings into Numbers 271
String Streams 272
Strings of International Characters 273
Strings of wchar_t Characters 274
Objects That Contain Unicode Strings 275
Raw String Literals 275
Summary 277
Chapter 8: Defining Functions 280
Segmenting Your Programs 280
Functions in Classes 281
Characteristics of a Function 281
Defining Functions 281
The Function Body 283
Return Values 285
How the return Statement Works 285
Function Declarations 286
Function Prototypes 287
Passing Arguments to a Function 287
Pass-by-Value 288
Passing a Pointer to a Function 289
Passing an Array to a Function 290
const Pointer Parameters 293
Passing a Multidimensional Array to a Function 294
Pass-by-Reference 296
References vs. Pointers 296
Input vs. Output Parameters 298
Passing Arrays by Reference 300
References and Implicit Conversions 302
String Views: The New Reference-to-const-string 303
Using String View Function Parameters 304
Default Argument Values 306
Multiple Default Parameter Values 306
Arguments to main() 308
Returning Values from a Function 309
Returning a Pointer 309
Returning a Reference 313
Returning vs. Output Parameters 314
Return Type Deduction 315
Return Type Deduction and References 316
Working with Optional Values 316
std::optional 317
Static Variables 320
Inline Functions 320
Function Overloading 321
Overloading and Pointer Parameters 323
Overloading and Reference Parameters 324
Overloading and const Parameters 325
Overloading with const Pointer Parameters 326
Overloading and Reference-to-const Parameters 327
Overloading and Default Argument Values 327
Recursion 328
Basic Examples 329
Recursive Algorithms 330
The Quicksort Algorithm 331
The main() Function 331
The extract_words() Function 333
The swap() Function 333
The sort() Functions 334
The max_word_length() Function 335
The show_words() Function 336
Summary 337
Chapter 9: Function Templates 342
Function Templates 342
Creating Instances of a Function Template 343
Template Type Parameters 345
Explicit Template Arguments 346
Function Template Specialization 346
Function Templates and Overloading 347
Function Templates with Multiple Parameters 349
Return Type Deduction for Templates 351
decltype() and Trailing Return Types 351
decltype(auto) and decltype() vs. auto 353
Default Values for Template Parameters 353
Nontype Template Parameters 354
Templates for Functions with Fixed-Size Array Arguments 355
Summary 357
Chapter 10: Program Files and Preprocessing Directives 359
Understanding Translation Units 359
The One Definition Rule 360
Program Files and Linkage 361
Determining Linkage for a Name 361
External Functions 361
External Variables 363
const Variables with External Linkage 364
Internal Names 365
Preprocessing Your Source Code 366
Defining Preprocessor Macros 367
Defining Function-Like Macros 368
Preprocessor Operators 370
Undefining Macros 371
Including Header Files 372
Preventing Duplication of Header File Contents 372
Your First Header File 374
Namespaces 375
The Global Namespace 375
Defining a Namespace 376
Applying using Declarations 378
Functions and Namespaces 379
Unnamed Namespaces 381
Nested Namespaces 382
Namespace Aliases 384
Logical Preprocessing Directives 384
The Logical #if Directive 384
Testing for Specific Identifier Values 385
Multiple-Choice Code Selection 385
Standard Preprocessing Macros 387
Testing for Available Headers 388
Debugging Methods 389
Integrated Debuggers 389
Preprocessing Directives in Debugging 390
Using the assert() Macro 393
Switching Off assert() Macros 394
Static Assertions 395
Summary 397
Chapter 11: Defining Your Own Data Types 400
Classes and Object-Oriented Programming 400
Encapsulation 401
Data Hiding 402
Inheritance 404
Polymorphism 405
Terminology 406
Defining a Class 407
Constructors 409
Default Constructors 409
Defining a Class Constructor 410
Using the default Keyword 412
Defining Functions and Constructors Outside the Class 412
Default Constructor Parameter Values 414
Using a Member Initializer List 415
Using the explicit Keyword 415
Delegating Constructors 418
The Copy Constructor 419
Implementing the Copy Constructor 420
Accessing Private Class Members 421
The this Pointer 423
Returning this from a Function 423
const Objects and const Member Functions 425
const Member Functions 425
const Correctness 427
Overloading on const 428
Casting Away const 430
Using the mutable Keyword 430
Friends 431
The Friend Functions of a Class 432
Friend Classes 434
Arrays of Class Objects 434
The Size of a Class Object 436
Static Members of a Class 437
Static Member Variables 437
Accessing Static Member Variables 441
Static Constants 442
Static Member Variables of the Class Type 443
Static Member Functions 444
Destructors 445
Using Pointers as Class Members 448
The Truckload Example 448
Defining the Package Class 451
Defining the Truckload Class 452
Traversing the Boxes Contained in a Truckload 454
Adding and Removing Boxes 456
Putting It All Together 458
Nested Classes 461
Nested Classes with Public Access 462
A Better Mechanism for Traversing a Truckload: Iterators 462
Summary 466
Chapter 12: Operator Overloading 469
Implementing Operators for a Class 469
Operator Overloading 470
Implementing an Overloaded Operator 470
Nonmember Operator Functions 473
Implementing Full Support for an Operator 473
Implementing All Comparison Operators in a Class 476
Operators That Can Be Overloaded 478
Restrictions and Key Guideline 479
Operator Function Idioms 481
Overloading the < <
Overloading the Arithmetic Operators 483
Implementing One Operator in Terms of Another 487
Member vs. Nonmember Functions 489
Operator Functions and Implicit Conversions 490
Overloading Unary Operators 491
Overloading the Increment and Decrement Operators 493
Overloading the Subscript Operator 494
Modifying the Result of an Overloaded Subscript Operator 498
Function Objects 500
Overloading Type Conversions 502
Potential Ambiguities with Conversions 503
Overloading the Assignment Operator 503
Implementing the Copy Assignment Operator 503
Copy Assignment vs. Copy Construction 507
Assigning Different Types 508
Summary 508
Chapter 13: Inheritance 511
Classes and Object-Oriented Programming 511
Hierarchies 512
Inheritance in Classes 513
Inheritance vs. Aggregation 513
Deriving Classes 514
protected Members of a Class 517
The Access Level of Inherited Class Members 518
Access Specifiers and Class Hierarchies 519
Choosing Access Specifiers in Class Hierarchies 520
Changing the Access Specification of Inherited Members 521
Constructors in a Derived Class 522
The Copy Constructor in a Derived Class 526
The Default Constructor in a Derived Class 528
Inheriting Constructors 528
Destructors Under Inheritance 529
The Order in Which Destructors Are Called 531
Duplicate Member Variable Names 531
Duplicate Member Function Names 532
Multiple Inheritance 533
Multiple Base Classes 533
Inherited Member Ambiguity 534
Repeated Inheritance 539
Virtual Base Classes 540
Converting Between Related Class Types 541
Summary 542
Chapter 14: Polymorphism 544
Understanding Polymorphism 544
Using a Base Class Pointer 544
Calling Inherited Functions 546
Virtual Functions 549
Requirements for Virtual Function Operation 553
Using override 553
Using final 554
Virtual Functions and Class Hierarchies 555
Access Specifiers and Virtual Functions 556
Default Argument Values in Virtual Functions 558
Using References to Call Virtual Functions 560
Polymorphic Collections 561
Destroying Objects Through a Pointer 562
Virtual Destructors 564
Converting Between Pointers to Class Objects 565
Dynamic Casts 567
Casting Pointers Dynamically 567
Converting References 570
Calling the Base Class Version of a Virtual Function 571
Calling Virtual Functions from Constructors or Destructors 572
The Cost of Polymorphism 574
Determining the Dynamic Type 576
Pure Virtual Functions 580
Abstract Classes 580
Abstract Classes as Interfaces 583
Summary 586
Chapter 15: Runtime Errors and Exceptions 589
Handling Errors 589
Understanding Exceptions 590
Throwing an Exception 591
The Exception-Handling Process 594
Code That Causes an Exception to Be Thrown 595
Nested try Blocks 596
How It Works 599
Class Objects as Exceptions 599
Matching a Catch Handler to an Exception 601
How It Works 604
Catching Derived Class Exceptions with a Base Class Handler 604
Rethrowing Exceptions 607
Unhandled Exceptions 609
Catching All Exceptions 611
Functions That Don’t Throw Exceptions 613
The noexcept Specifier 613
Exceptions and Destructors 614
Exceptions and Resource Leaks 615
Resource Acquisition Is Initialization 617
Standard RAII Classes for Dynamic Memory 619
Standard Library Exceptions 620
The Exception Class Definitions 622
Using Standard Exceptions 624
Throwing Standard Exceptions Directly 624
Deriving Your Own Exception Classes 624
Summary 627
Chapter 16: Class Templates 631
Understanding Class Templates 632
Defining Class Templates 633
Template Parameters 633
A Simple Class Template 634
Defining Member Functions of a Class Template 636
Constructor Templates 636
The Destructor Template 637
Subscript Operator Templates 638
The Assignment Operator Template 640
Instantiating a Class Template 645
Class Template Argument Deduction 650
Nontype Class Template Parameters 652
Templates for Member Functions with Nontype Parameters 654
Arguments for Nontype Parameters 659
Nontype Template Arguments vs. Constructor Arguments 659
Default Values for Template Parameters 660
Explicit Template Instantiation 661
Class Template Specialization 661
Defining a Class Template Specialization 662
Partial Template Specialization 662
Choosing Between Multiple Partial Specializations 663
Using static_assert() in a Class Template 663
Friends of Class Templates 665
Class Templates with Nested Classes 667
Function Templates for Stack Members 669
Disambiguating Dependent Names 674
Summary 676
Chapter 17: Move Semantics 679
Lvalues and Rvalues 680
Rvalue References 681
Moving Objects 682
Traditional Workarounds 685
Defining Move Members 686
Move Constructors 686
Move Assignment Operators 688
Explicitly Moved Objects 690
Move-Only Types 690
Extended Use of Moved Objects 691
A Barrel of Contradictions 693
std::move() Does Not Move 693
An Rvalue Reference Is an Lvalue 694
Defining Functions Revisited 694
Pass-by-Rvalue-Reference 694
The Return of Pass-by-Value 696
Return-by-Value 699
Defining Move Members Revisited 701
Always Add noexcept 701
Moving Within Standard Library Containers 704
The “Move-and-Swap” Idiom 706
Special Member Functions 707
Default Move Members 708
The Rule of Five 709
The Rule of Zero 710
Summary 711
Chapter 18: First-Class Functions 713
Pointers to Functions 714
Defining Pointers to Functions 714
Callback Functions for Higher-Order Functions 717
Type Aliases for Function Pointers 719
Function Objects 721
Basic Function Objects 721
Standard Function Objects 723
Parameterized Function Objects 724
Lambda Expressions 725
Defining a Lambda Expression 726
Naming a Lambda Closure 727
Passing a Lambda Expression to a Function Template 727
The Capture Clause 729
Capturing by Value 729
Capturing by Reference 731
Capturing Specific Variables 731
Capturing the this Pointer 732
The std::function< >
Summary 736
Chapter 19: Containers and Algorithms 739
Containers 739
Sequence Containers 740
Arrays 740
Lists 740
Key Operations 742
Stacks and Queues 743
LIFO vs. FIFO Semantics 743
Priority Queues 745
Sets 745
Ordered Sets 747
Unordered Sets 747
Maps 748
Elements of a Map 749
Counting Words 750
Iterators 753
The Iterator Design Pattern 753
Iterators for Standard Library Containers 755
Creating and Working with Standard Iterators 755
Different Flavors of Iterators 756
Traversing Elements of a Container 757
Const Iterators 759
Inserting in and Erasing from Sequence Containers 760
Altering Containers During Iteration 762
Iterators for Arrays 764
Algorithms 765
A First Example 766
Finding Elements 768
Outputting Multiple Values 770
The Remove-Erase Idiom 771
Sorting 773
Parallel Algorithms 774
Summary 774
Index 778
Erscheint lt. Verlag | 24.3.2018 |
---|---|
Zusatzinfo | XXVIII, 771 p. 82 illus. |
Verlagsort | Berkeley |
Sprache | englisch |
Themenwelt | Mathematik / Informatik ► Informatik ► Programmiersprachen / -werkzeuge |
Schlagworte | C++ • C++17 • Code • Ivor Horton • programming • Software • Tutorial |
ISBN-10 | 1-4842-3366-2 / 1484233662 |
ISBN-13 | 978-1-4842-3366-5 / 9781484233665 |
Haben Sie eine Frage zum Produkt? |
Größe: 9,9 MB
DRM: Digitales Wasserzeichen
Dieses eBook enthält ein digitales Wasserzeichen und ist damit für Sie personalisiert. Bei einer missbräuchlichen Weitergabe des eBooks an Dritte ist eine Rückverfolgung an die Quelle möglich.
Dateiformat: PDF (Portable Document Format)
Mit einem festen Seitenlayout eignet sich die PDF besonders für Fachbücher mit Spalten, Tabellen und Abbildungen. Eine PDF kann auf fast allen Geräten angezeigt werden, ist aber für kleine Displays (Smartphone, eReader) nur eingeschränkt geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen dafür einen PDF-Viewer - z.B. den Adobe Reader oder Adobe Digital Editions.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen dafür einen PDF-Viewer - z.B. die kostenlose Adobe Digital Editions-App.
Zusätzliches Feature: Online Lesen
Dieses eBook können Sie zusätzlich zum Download auch online im Webbrowser lesen.
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
aus dem Bereich