• Tidak ada hasil yang ditemukan

C+++ HOW TO PROGRAM

N/A
N/A
Ali Basher

Academic year: 2023

Membagikan "C+++ HOW TO PROGRAM "

Copied!
1065
0
0

Teks penuh

To access the C++ How to Program, Ninth Edition, Companion website for the first time, you will need to log on to the Internet using a computer with an Internet connection and a Web browser. Java™ How to Program, Late Version Objects, 8/E Internet and World Wide Web How to Program, 5/E Visual Basic®2012 How to Program.

Confusing the Equality ( == ) and Assignment ( = ) Operators 185

Function Definitions with Multiple Parameters 205 6.5 Function Prototypes and Argument Coercion 210

Case Study: Game of Chance; Introducing enum 219

Function Call Stack and Activation Records 231

Example Using Recursion: Fibonacci Series 252

Examples Using array s 281 .1 Declaring an array and Using a Loop to Initialize

Initializing an array in a Declaration with an

Specifying an array ’s Size with a Constant Variable

Using Bar Charts to Display array Data Graphically 286 7.4.6 Using the Elements of an array as Counters 288

Case Study: Class GradeBook Using an array to Store Grades 295

Pointer Variable Declarations and Initialization 335

Nonconstant Pointer to Nonconstant Data 347 8.6.2 Nonconstant Pointer to Constant Data 347

Pointer Expressions and Pointer Arithmetic 353 8.9 Relationship Between Pointers and Built-In Arrays 355

Class Scope and Accessing Class Members 385

Time Class Case Study: Constructors with Default Arguments 387

When Constructors and Destructors Are Called 393 9.8 Time Class Case Study: A Subtle Trap—Returning a

Using the Overloaded Operators of Standard Library Class string 435

Overloading the Binary Stream Insertion and Stream Extraction

Overloading the Unary Prefix and Postfix ++ and -- Operators 445

Operators as Member vs. Non-Member Functions 466

Relationship between Base and Derived Classes 486 .1 Creating and Using a CommissionEmployee Class 486

Creating a CommissionEmployee –

Introduction to Polymorphism: Polymorphic Video Game 519 12.3 Relationships Among Objects in an Inheritance Hierarchy 519

Virtual Functions and Virtual Destructors 526

Abstract Classes and Pure virtual Functions 533 12.6 Case Study: Payroll System Using Polymorphism 535

Demonstrating Polymorphic Processing 546 12.7 (Optional) Polymorphism, Virtual Functions and Dynamic

Case Study: Payroll System Using Polymorphism and Runtime Type Information with Downcasting, dynamic_cast , typeid

Classic Streams vs. Standard Streams 564

Stream Input/Output Classes and Objects 565

Character Output Using Member Function put 568

Unformatted I/O Using read , write and gcount 572

User-Defined Output Stream Manipulators 577 13.7 Stream Format States and Stream Manipulators 578

Uppercase/Lowercase Control ( uppercase ) 585 13.7.7 Specifying Boolean Format ( boolalpha ) 585

Tying an Output Stream to an Input Stream 590

Random-Access Files 611

Writing Data Randomly to a Random-Access File 617 14.9 Reading from a Random-Access File Sequentially 619

Basic Searching and Sorting Algorithms 706

Example: Handling an Attempt to Divide by Zero 741

Constructors, Destructors and Exception Handling 751

Class unique_ptr and Dynamic Memory Allocation 755

Function Template to Manipulate a Class-Template

Default Arguments for Template Type Parameters 773

Stacks 794

Merge Sort (A Recursive Implementation) 837

Finding Substrings and Characters in a string 859

Conversion to Pointer-Based char * Strings 864

Example: Card Shuffling and Dealing Simulation 882

Search Functions of the C String-Handling Library 915 22.11 Memory Functions of the C String-Handling Library 919

Pointers to Class Members ( .* and ->* ) 948

Multiple Inheritance and virtual Base Classes 955

Abbreviating Binary Numbers as Octal and Hexadecimal Numbers 976 D.3 Converting Octal and Hexadecimal Numbers to Binary Numbers 977

Online Chapters and Appendices

25 ATM Case Study, Part 1

Object-Oriented Design with the UML 25-1

26 ATM Case Study, Part 2

Implementing an Object-Oriented Design 26-1

Contents xix 26.2 Getting Started Programming ATM System Classes 26-2 26.3 Incorporating Inheritance into the ATM System 26-8.

G UML 2: Additional Diagram Types G-1

H Using the Visual Studio Debugger H-1

K Test Driving a C++ Program on Mac OS X K-1

All source code is available at www.deitel.com/books/cpphtp9 and www.pearsonhighered.com/. If you have any questions while reading the book, it's easy to contact us at [email protected] – we'll reply immediately.

C++11 Standard

Read the online section Before You Begin (www.deitel.com/.books/cpphtp9/cpphtp9_BYB.pdf) to learn how to set up your Linux, Windows, or Apple OS X computer to run the hundreds of code examples . For book updates, visit www.deitel.com/books/cpphtp9 and join our social media communities on Facebook (www.deitel.com/DeitelFan), Twitter (@deitel), Google+ (gplus.to/deitel) and LinkedIn (bit .ly/DeitelLinkedIn) and subscribe to the Deitel®Buzz Online newsletter (www.deitel.com/newsletter/subscribe.html).

Fig. 1 | A sampling of C++11 features in C++ How to Program, 9/e.
Fig. 1 | A sampling of C++11 features in C++ How to Program, 9/e.

Object-Oriented Programming

We determine the classes needed to implement that system, the properties the classes must have, the behavior the classes must exhibit, and we specify how the classes must interact with each other to meet the system requirements. We offer a rich multi-chapter treatment of data structures—see the Data Structures module in the chapter dependency graph (Fig. 6).

Pedagogic Features

The audience. The examples are accessible to computer science, information technology, software engineering, and business students in introductory and intermediate C++ courses. Interesting, fun and challenging exercises. Each chapter concludes with an extensive set of exercises, including simple recall of important terminology and concepts, identifying errors in code samples, writing individual program statements, writing small parts of C++ classes and function members and non-members, writing entire programs, and implementing larger projects.

Fig. 3 | A sampling of the book’s exercises. (Part 2 of 2.)
Fig. 3 | A sampling of the book’s exercises. (Part 2 of 2.)

Other Features

Secure C++ Programming

Online Content

Dependency Chart

Teaching Approach

Obtaining the Software Used in C++ How to Program, 9/e

Instructor Supplements

Customizable PowerPoint® slides that contain all the code and figures in the text, plus bulleted articles that summarize key points in the text.

Online Practice and Assessment with MyProgrammingLab™

Acknowledgments

About the Authors

Corporate Training from Deitel & Associates, Inc

Hardware and Software

  • Moore’s Law
  • Computer Organization

A computer consists of various devices referred to as hardware (eg the keyboard, screen, mouse, hard drives, memory, DVD drives and processing units). This remarkable trend is often called Moore's Law, named after the person who identified it in the 1960s, Gordon Moore, co-founder of Intel—the leading manufacturer of the processors in today's computers and embedded systems.

Data Hierarchy

It is remarkable that the impressive functions performed by computers involve only the simplest manipulations of 0s and 1s—examining the value of a bit, setting the value of a bit, and returning the value of a bit (from 1 to 0 or from 0 to 1). C++ supports several character sets, including 16-bit Unicode® characters that consist of two bytes, each consisting of eight bits.

Fig. 1.3 | Data hierarchy.
Fig. 1.3 | Data hierarchy.

Machine Languages, Assembly Languages and High- Level Languages

To further speed up the programming process, high-level languages ​​were developed in which single statements could be written to accomplish important tasks. The process of compiling a large high-level language program into machine language can take a significant amount of computer time. Interpreters were developed to run high-level language programs directly (without the need for compilation), although slower than compiled programs. Scripting languages ​​such as popular web languages ​​JavaScript and PHP are processed by interpreters.

Programming Languages

C# Microsoft's three object-oriented primary programming languages ​​are Visual Basic (based on the original Basic), Visual C++. based on C++) and C# (based on C++ and Java, and developed for integrating the Internet and the Web into desktop applications). Perl Perl (Practical Extraction and Report Language), one of the most widely used object-oriented scripting languages ​​for web programming, was developed in 1987 by Larry Wall.

Introduction to Object Technology

Classes encapsulate (i.e., wrap) attributes and member functions in objects: The attributes and member functions of an object are closely related. By programming in such a language, called object-oriented programming (OOP), you can implement object-oriented design as a working system.

Typical C++ Development Environment

Alinker links the object code with the code for the missing functions to produce an executable program (with no missing pieces). Linker associates the object code with the libraries, creates an executable file and saves it to disk.

Fig. 1.8 | Typical C++ development environment—compilation phase.
Fig. 1.8 | Typical C++ development environment—compilation phase.

Test-Driving a C++ Application

Try again.", which means that the value you entered is greater than the number the application chose as the correct guess. Try again.", because the value you entered is still greater than the number the app selected as the correct guess. application if selected the correct guess. .

Fig. 1.12 | Opening a Command Prompt window and changing the directory.
Fig. 1.12 | Opening a Command Prompt window and changing the directory.

Operating Systems

  • Windows—A Proprietary Operating System
  • Linux—An Open-Source Operating System
  • Google’s Android

Enterprise systems companies, such as IBM, Oracle, and many others, have made significant investments in open source Linux development. A great example is Facebook, which was launched out of a college dorm room and built with open source software.

The Internet and World Wide Web

TheURL (Uniform Resource Locator) specifies the address (ie, the location) of the web page displayed in the browser window. Hypertext Transfer Protocol Secure (HTTPS) is the standard for transferring encrypted data on the Web.

Some Key Software Development Terminology

LAMP LAMP is an acronym for a set of open source technologies that many developers use to build web applications - meaning Linux, Apache, MySQL and PHP (or Perl or Python - two other languages ​​used for similar purposes). PHP is the most popular open source Internet server-side "scripting" language for Internet application development.

C++11 and the Open Source Boost Libraries

The Boost libraries can be used by C++ programmers working on a wide variety of platforms with many different compilers. They can be used to validate data to make sure it is in a certain format, to replace parts of a string with another, or to split a string.

Keeping Up to Date with Information Technologies

Boost provides C++ programmers with useful libraries that work well with the existing C++ standard library. Among other things, we review the libraries and provide code examples for the "regular expression" and "smart pointer" libraries.

Web Resources

Self-Review Exercises

Answers to Self-Review Exercises

Exercises

Making a Difference

You have been asked to create a program that can process a paragraph of text and replace gender-specific words with gender-neutral ones. Assuming you're given a list of gender-specific words and their gender-neutral replacements (eg, replace "wife" with "husband," "man" with "person," "girl" with "child," etc.) . on), explain the procedure you would use to read a paragraph of text and manually perform these substitutions.

Making a Difference Resources

Modifying Our First C++ Program

When you write a new program or modify an existing one, you must update your comments with the program code. A single statement can print multiple lines using newline characters, as in line 8 of Fig.

Another C++ Program: Adding Integers

When the computer executes the previous statement, it waits for the user to enter a value for variable number 1. Calculating the sum of the values ​​supplied by the user The assignment statement on line 19.

Memory Concepts

Destd::endlstream manipulator executes a newline and "then reads the output buffer." This simply means that on some systems the output accumulates in the machine until there is enough to "make it worth it". A powerful feature of C++ is that you can create your own data types called classes (we introduce this feature in Chapter 3 and go into more detail in Chapter 9).

Arithmetic

If an expression contains multiple addition and subtraction operations, operators are used from left to right. Caution: If you have an expression like (a + b) * (c - d) in which two sets of parentheses are not nested but appear "at the same level", the C++ standard does not specify the order in which these parenthesized subexpressions will be evaluated.].

Fig. 2.10 | Precedence of arithmetic operators.
Fig. 2.10 | Precedence of arithmetic operators.

Decision Making: Equality and Relational Operators

From this point on in the book, we will use the previous directive in our programs.1. All of these operators, except the assignment operator =, are bound from left to right.

Fig. 2.13 | Comparing integers using if statements, relational operators and equality operators.
Fig. 2.13 | Comparing integers using if statements, relational operators and equality operators.

Wrap-Up

Summary

Defining a Member Function with a Parameter

The rest of the course name will have to be read by subsequent input operations. When you run this program, the member function displays as part of the welcome message the name of the course you type (in our sample run, CS101 Introduction to C++ Programming).

Fig. 3.3 | Define class GradeBook with a member function that takes a parameter, create a
Fig. 3.3 | Define class GradeBook with a member function that takes a parameter, create a

Data Members, set Member Functions and get Member Functions

The advantage of making a CourseName data member is that all member functions of the class can manipulate any data member that appears in the class definition (in this case, CourseName). Only member functions of that class (and "friends" of the class, as you'll see in Chapter 9) can manipulate the private data members of a class.

Fig. 3.5 | Defining and testing class GradeBook with a data member and set and get member functions
Fig. 3.5 | Defining and testing class GradeBook with a data member and set and get member functions

Initializing Objects with Constructors

The default constructor does not initialize the data members of the class, but calls the default constructor for each data member that is an object of another class. Such a default constructor will call the default constructor for each data member that is an object of a different class and will perform additional initialization specified by you.

Fig. 3.7 | Instantiating multiple objects of the GradeBook class and using the GradeBook
Fig. 3.7 | Instantiating multiple objects of the GradeBook class and using the GradeBook

Placing a Class in a Separate File for Reusability

To test classGradeBook (defined in Figure 3.9), you must write a separate source code file that contains amainfunction (such as Figure 3.10) that instantiates and uses class objects. The compiler creates only one copy of the class's member functions and shares that copy with all objects of the class.

Fig. 3.9 | GradeBook class definition in a separate file from main .
Fig. 3.9 | GradeBook class definition in a separate file from main .

Separating Interface from Implementation

This “links” each member function to the (now separate) GradeBook class definition (Fig. 3.11), which declares the class's member functions and data members. Thus, the diagram shows what is required for both the class implementation programmer and the client code programmer.

Fig. 3.12 | GradeBook member-function definitions represent the implementation of class
Fig. 3.12 | GradeBook member-function definitions represent the implementation of class

Validating Data with set Functions

10 explicit routine (std::string); // constructor initializes courseName 11 void setCourseName( std::string ); // set the course name. 3.17 | Create and manage aGradeBookobject in which the course name is limited to 25 characters.

Fig. 3.16 | Member-function definitions for class GradeBook with a set function that validates the length of data member courseName .
Fig. 3.16 | Member-function definitions for class GradeBook with a set function that validates the length of data member courseName .

Wrap-Up

A data member is declared in a class, but not in the body of any of the class's member functions. The class attributes must include the person's first name, last name, and date of birth (consisting of separate attributes for the month, day, and year of birth).

Pseudocode

Control Structures

The solid circle at the top of the diagram represents the initial state of the activity—the beginning of the workflow before the program performs the modeled activities. The solid circle surrounded by an empty circle that appears at the bottom of the activity diagram represents the final state—the end of the workflow after the program completes its activities.

Fig. 4.3 | C++ keywords.
Fig. 4.3 | C++ keywords.

Each program combines as many of each of these control statements as is appropriate for the algorithm the program is implementing. Imagine seven containers, each containing only empty UML activity diagrams of one of the seven types of control statements.

As we will see, the precedence of the conditional operator is low, so the parentheses in the preceding expression are required. The braces ({}) indicate to the compiler that the second statement is in the body of the first, and the second is connected to the first.

A decision symbol has one transition arrow pointing to the diamond and two or more transition arrows pointing out of the diamond, indicating possible transitions from that point. A merge symbol has two or more transition arrows pointing to a diamond and only one transition arrow pointing to a diamond, indicating multiple activity streams that are merging to continue the activity.

Fig. 4.6 | while repetition statement UML activity diagram.
Fig. 4.6 | while repetition statement UML activity diagram.

Formulating Algorithms: Counter-Controlled Repetition

Acounteris a variable used to count - in this case, the grade counter indicates which of the 10 grades will be entered by the user. This line corresponds to the "Enter next grade" pseudocode statement. Line 54 adds the new grade entered by the user to the total.

Fig. 4.8 | Class average problem using counter-controlled repetition: GradeBook header.
Fig. 4.8 | Class average problem using counter-controlled repetition: GradeBook header.

Formulating Algorithms: Sentinel-Controlled Repetition

When the current manipulators set and set precision are used in a program, the printed value is rounded to the number of decimal places indicated by the value passed to the set precision (eg, the value2 in line 75), although the value in memory remains unchanged. We declared those variables as asints because we can't control what the user actually enters - the user can enter negative values.

Fig. 4.11 | Sentinel-controlled class average problem pseudocode algorithm.
Fig. 4.11 | Sentinel-controlled class average problem pseudocode algorithm.

Formulating Algorithms: Nested Control Statements

Display a summary of test results showing the number of students who passed and the number of students who failed. At the end of the second sample run, the condition in line 35 is true—more than eight students passed the exam, so the program issues a message indicating that the instructor should receive a bonus.

Fig. 4.15 | Pseudocode for examination-results problem. (Part 1 of 2.)
Fig. 4.15 | Pseudocode for examination-results problem. (Part 1 of 2.)

Assignment Operators

Increment and Decrement Operators

Preincrementing (or predecrementing) causes a variable to be incremented (decremented) by 1, and then the variable's new value is used in the expression in which it appears. Postincrement (or postdecrement) causes the current value of a variable to be used in the expression in which it appears, and then the value of the variable is incremented (decremented) by 1.

Figure 4.19 demonstrates the difference between the prefix increment and postfix incre- incre-ment versions of the ++ increment operator
Figure 4.19 demonstrates the difference between the prefix increment and postfix incre- incre-ment versions of the ++ increment operator

Wrap-Up

Ask the user for the desired precision of e (that is, the number of terms in the summation). c) Write a program that calculates the value of exby using the formula. Ask the user for the desired precision of e (that is, the number of terms in the summation).

If the loop-continue condition is initially false, the body of the for statement is not executed. Often the control variable is printed or used in calculations in the body of afor.

Figure 5.3 takes a closer look at the for statement header (line 10) of Fig. 5.2. Notice that the for statement header “does it all”—it specifies each of the items needed for  counter-controlled repetition with a control variable
Figure 5.3 takes a closer look at the for statement header (line 10) of Fig. 5.2. Notice that the for statement header “does it all”—it specifies each of the items needed for counter-controlled repetition with a control variable

Examples Using the for Statement

Gambar

Fig. 1.4 | Levels of the data hierarchy. (Part 1 of 2.)
Fig. 1.10 | Typical C++ development environment—loading phase.
Fig. 1.15 | Entering a second guess and receiving feedback.
Fig. 1.17 | Playing the game again.
+7

Referensi

Dokumen terkait