1. Trang chủ
  2. » Công Nghệ Thông Tin

Herbert schild c++ from the ground up

625 1,8K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề C++ From the Ground Up
Tác giả Herbert Schildt
Trường học University of Illinois
Chuyên ngành Computer Science
Thể loại sách về lập trình
Năm xuất bản 2003
Thành phố New York
Định dạng
Số trang 625
Dung lượng 4,95 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Đây là quyển sách tiếng anh về lĩnh vực công nghệ thông tin cho sinh viên và những ai có đam mê. Quyển sách này trình về lý thuyết ,phương pháp lập trình cho ngôn ngữ C và C++.

Trang 2

C++ from the Ground Up

Third Edition

Trang 3

About the Author

Herbert Schildt is the world’s leading

programming author He is an authority on the

C, C++, Java, and C# languages, and is a masterWindows programmer His programming bookshave sold more than 3 million copies worldwideand have been translated into all major foreignlanguages He is the author of numerous bestsellers,

including C++: The Complete Reference, C#: The

Complete Reference, Java 2: The Complete Reference, C: The Complete Reference, C++ From the Ground Up, C++: A Beginner’s Guide, C#: A Beginner’s Guide, and Java 2: A Beginner’s Guide Schildt holds a master’s

degree in computer science from the University ofIllinois He can be reached at his consulting office

at (217) 586-4683

Trang 4

C++ from the Ground Up

Trang 5

2600 Tenth StreetBerkeley, California 94710U.S.A

To arrange bulk purchase discounts for sales promotions, premiums, or fund-raisers,

please contact McGraw-Hill/Osborne at the above address For information on

translations or book distributors outside the U.S.A., please see the InternationalContact Information page immediately following the index of this book

C++ from the Ground Up, Third Edition

Copyright © 2003 by The McGraw-Hill Companies All rights reserved Printed inthe United States of America Except as permitted under the Copyright Act of

1976, no part of this publication may be reproduced or distributed in any form

or by any means, or stored in a database or retrieval system, without the priorwritten permission of publisher, with the exception that the program listings may

be entered, stored, and executed in a computer system, but they may not bereproduced for publication

1234567890 DOC DOC 019876543ISBN 0-07-222897-0

Cover Series Design

John Nedwidek, emdesign

Cover Illustration

Lance Ravella

This book was composed with Corel VENTURA™ Publisher

Information has been obtained by McGraw-Hill/Osborne from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill/Osborne, or others, McGraw-Hill/Osborne does not

guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information.

Trang 6

Preface xvii

1 The Story of C++ 1

The Origins of C++ 2

The Creation of C 2

Understanding the Need for C++ 4

C++ Is Born 5

The Evolution of C++ 6

What Is Object-Oriented Programming? 6

Encapsulation 7

Polymorphism 7

Inheritance 8

C++ Implements OOP 8

How C++ Relates to Java and C# 8

2 An Overview of C++ 11

Your First C++ Program 12

Entering the Program 12

Compiling the Program 13

Run the Program 14

A Line-by-Line Explanation 14

v

Trang 7

Handling Syntax Errors 16

A Second Simple Program 17

A More Practical Example 18

A New Data Type 19

A Quick Review 20

Functions 20

A Program with Two Functions 21

Function Arguments 22

Functions Returning Values 24

The main( ) Function 25

The General Form of C++ Functions 26

Some Output Options 26

Two Simple Commands 27

The if Statement 27

The for Loop 28

Blocks of Code 29

Semicolons and Positioning 30

Indentation Practices 31

C++ Keywords 31

Identifiers in C++ 32

The Standard C++ Library 32

3 The Basic Data Types 33

Declaration of Variables 35

Local Variables 35

Formal Parameters 36

Global Variables 37

Some Type Modifiers 38

Literals 41

Hexadecimal and Octal Literals 43

String Literals 43

Character Escape Sequences 44

Variable Initializations 45

Operators 46

Arithmetic Operators 46

Increment and Decrement 48

How C++ Got Its Name 49

Relational and Logical Operators 50

Expressions 53

Type Conversion in Expressions 53

Converting to and from bool 53

Casts 54

Spacing and Parentheses 55

Trang 8

4 Program Control Statements 57

The if Statement 58

The Conditional Expression 59

Nested ifs 60

The if-else-if Ladder 61

The for Loop 62

Some Variations on the for Loop 64

Missing Pieces 66

The Infinite Loop 66

Time Delay Loops 67

The switch Statement 67

Nested switch Statements 71

The while Loop 71

The do-while Loop 73

Using continue 74

Using break to Exit Loops 75

Nested Loops 76

Using the goto Statement 77

Putting Together the Pieces 78

5 Arrays and Strings 81

One-Dimensional Arrays 82

No Bounds Checking 84

Sorting an Array 85

Strings 86

Reading a String from the Keyboard 87

Some String Library Functions 89

strcpy 89

strcat 89

strcmp 90

strlen 91

Using the Null Terminator 93

Two-Dimensional Arrays 94

Multidimensional Arrays 96

Array Initialization 96

Unsized Array Initializations 100

Arrays of Strings 101

An Example Using String Arrays 102

6 Pointers 105

What Are Pointers? 106

The Pointer Operators 107

The Base Type Is Important 108

Assigning Values Through a Pointer 110

Trang 9

Pointer Expressions 110

Pointer Arithmetic 111

Pointer Comparisons 112

Pointers and Arrays 112

Indexing a Pointer 115

Are Pointers and Arrays Interchangeable? 116

Pointers and String Literals 117

A Comparison Example 117

Arrays of Pointers 118

The Null Pointer Convention 121

Multiple Indirection 122

Pointers and 16-bit Environments 122

Problems with Pointers 124

Uninitialized Pointers 124

Invalid Pointer Comparisons 124

Forgetting to Reset a Pointer 125

7 Functions, Part One: The Fundamentals 127

Scope Rules of Functions 128

Local Variables 128

Formal Parameters 134

Global Variables 134

Passing Pointers and Arrays 136

Calling Functions with Pointers 136

Calling Functions with Arrays 137

Passing Strings 140

argc and argv: Arguments to main( ) 141

Passing Numeric Command Line Arguments 144

Converting Numeric Strings to Numbers 145

The return Statement 145

Returning from a Function 146

Returning Values 147

void Functions 149

Functions That Return Pointers 149

Function Prototypes 151

Headers: A Closer Look 152

Old-Style versus Modern Function Parameter Declarations 153

Recursion 153

8 Functions, Part Two: References, Overloading, and Default Arguments 157

Two Approaches to Argument Passing 158

How C++ Passes Arguments 158

Using a Pointer to Create a Call-by-Reference 159

Trang 10

Reference Parameters 160

Declaring Reference Parameters 163

Returning References 164

Creating a Bounded Array 167

Independent References 168

A Few Restrictions When Using References 169

Function Overloading 170

The overload Anachronism 173

Default Function Arguments 173

Default Arguments versus Overloading 175

Using Default Arguments Correctly 177

Function Overloading and Ambiguity 177

9 More Data Types and Operators 181

The const and volatile Qualifiers 182

const 182

volatile 184

Storage Class Specifiers 185

auto 185

extern 186

static Variables 187

Register Variables 191

The Origins of the register Modifier 192

Enumerations 193

typedef 197

More Operators 197

Bitwise Operators 197

AND, OR, XOR, and NOT 198

The Shift Operators 202

The ? Operator 203

Compound Assignment 205

The Comma Operator 205

Multiple Assignments 206

Using sizeof 206

Dynamic Allocation Using new and delete 207

Initializing Dynamically Allocated Memory 210

Allocating Arrays 210

C’s Approach to Dynamic Allocation: malloc( ) and free( ) 211

Precedence Summary 213

10 Structures and Unions 215

Structures 216

Accessing Structure Members 218

Arrays of Structures 219

Trang 11

A Simple Inventory Example 219

Passing Structures to Functions 226

Assigning Structures 227

Pointers to Structures and the Arrow Operator 228

References to Structures 232

Arrays and Structures Within Structures 233

C Structure Versus C++ Structures 234

Bit-Fields 235

Unions 237

Anonymous Unions 242

Using sizeof to Ensure Portability 243

Moving On to Object-Oriented Programming 243

11 Introducing the Class 245

Class Fundamentals 246

The General Form of a class 250

A Closer Look at Class Member Access 250

Constructors and Destructors 252

Parameterized Constructors 255

An Initialization Alternative 259

Classes and Structures Are Related 260

Structures versus Classes 262

Unions and Classes Are Related 263

Inline Functions 264

Creating Inline Functions Inside a Class 265

Arrays of Objects 267

Initializing Object Arrays 268

Pointers to Objects 270

Object References 272

12 A Closer Look at Classes 273

Friend Functions 274

Overloading Constructors 278

Dynamic Initialization 280

Applying Dynamic Initialization to Constructors 280

Assigning Objects 282

Passing Objects to Functions 283

Constructors, Destructors, and Passing Objects 284

A Potential Problem When Passing Objects 285

Returning Objects 288

A Potential Problem When Returning Objects 289

Creating and Using a Copy Constructor 291

Copy Constructors and Parameters 292

Copy Constructors and Initializations 294

Trang 12

Using Copy Constructors When an Object Is Returned 295

Copy Constructors—Is There a Simpler Way? 296

The this Keyword 297

13 Operator Overloading 299

Operator Overloading Using Member Functions 300

Using Member Functions to Overload Unary Operators 303

Operator Overloading Tips and Restrictions 308

Nonmember Operator Functions 309

Order Matters 309

Using a Friend to Overload a Unary Operator 313

Overloading the Relational and Logical Operators 316

A Closer Look at the Assignment Operator 317

Overloading [ ] 320

Overloading ( ) 324

Overloading Other Operators 325

Another Example of Operator Overloading 325

14 Inheritance 331

Introducing Inheritance 332

Base Class Access Control 335

Using protected Members 337

Using protected for Inheritance of a Base Class 340

Reviewing public, protected, and private 342

Inheriting Multiple Base Classes 342

Constructors, Destructors, and Inheritance 343

When Constructors and Destructors Are Executed 343

Passing Parameters to Base Class Constructors 346

Granting Access 350

Reading C++ Inheritance Graphs 352

Virtual Base Classes 352

15 Virtual Functions and Polymorphism 357

Pointers to Derived Types 358

References to Derived Types 360

Virtual Functions 360

Virtual Functions Are Inherited 363

Why Virtual Functions? 365

A Simple Application of Virtual Functions 366

Pure Virtual Functions and Abstract Classes 370

Early versus Late Binding 372

Polymorphism and the Purist 373

16 Templates 375

Generic Functions 376

A Function with Two Generic Types 378

Explicitly Overloading a Generic Function 379

Trang 13

Overloading a Function Template 381

Using Standard Parameters with Template Functions 382

Generic Function Restrictions 383

Creating a Generic abs( ) Function 383

Generic Classes 384

An Example with Two Generic Data Types 387

Creating a Generic Array Class 388

Using Non-Type Arguments with Generic Classes 389

Using Default Arguments with Template Classes 391

Explicit Class Specializations 393

17 Exception Handling 395

Exception Handling Fundamentals 396

exit( ) and abort( ) 398

Catching Class Types 401

Using Multiple catch Statements 402

Options for Exception Handling 404

Catching All Exceptions 404

Restricting Exceptions Thrown by a Function 406

Rethrowing an Exception 408

Handling Exceptions Thrown by new 409

The nothrow Alternative 410

Overloading new and delete 411

Overloading the nothrow Version of new 415

18 The C++ I/O System 417

Old VS Modern C++ I/O 418

C++ Streams 418

The C++ Predefined Streams 419

The C++ Stream Classes 419

Overloading the I/O Operators 420

Creating Inserters 421

Using Friend Functions to Overload Inserters 423

Overloading Extractors 424

C I/O Versus C++ I/O 426

Formatted I/O 426

Formatting with the ios Member Functions 426

Using I/O Manipulators 431

Creating Your Own Manipulator Functions 433

File I/O 435

Opening and Closing a File 435

Reading and Writing Text Files 438

Unformatted Binary I/O 439

Reading and Writing Blocks of Data 441

Detecting EOF 442

A File Comparison Example 443

Trang 14

More Binary I/O Functions 444

Random Access 446

Checking I/O Status 448

Customized I/O and Files 449

19 Run-Time Type ID and the Casting Operators 451

Run-Time Type Identification (RTTI) 452

A Simple Application of Run-Time Type ID 456

typeid Can Be Applied to Template Classes 458

The Casting Operators 462

dynamic_cast 462

const_cast 467

static_cast 468

reinterpret_cast 469

The Traditional Cast Versus the Four Casting Operators 470

20 Namespaces and Other Advanced Topics 471

Namespaces 472

Namespace Fundamentals 472

using 475

Unnamed Namespaces 477

The std Namespace 478

Pointers to Functions 480

Finding the Address of an Overloaded Function 483

Static Class Members 484

const Member Functions and mutable 486

Explicit Constructors 488

An Interesting Benefit from Implicit Constructor Conversion 490

The Member Initialization Syntax 490

Using the asm Keyword 493

Linkage Specification 493

The * and –>* Pointer-to-Member Operators 495

Creating Conversion Functions 497

21 Introducing the Standard Template Library 499

An Overview of the STL 500

The Container Classes 502

Vectors 504

Accessing a Vector Through an Iterator 508

Inserting and Deleting Elements in a Vector 509

Storing Class Objects in a Vector 510

The Power of Iterators 513

Lists 514

Sort a List 519

Merging One List with Another 520

Storing Class Objects in a List 521

Trang 15

Maps 523

Storing Class Objects in a Map 528

Algorithms 529

Counting 532

Removing and Replacing Elements 533

Reversing a Sequence 535

Transforming a Sequence 535

Exploring the Algorithms 537

The string Class 537

Some string Member Functions 541

Putting Strings into Other Containers 545

Final Thoughts on the STL 545

22 The C++ Preprocessor 547

#define 548

Function-Like Macros 550

#error 552

#include 552

Conditional Compilation Directives 553

#if, #else, #elif, and #endif 553

#ifdef and #ifndef 555

#undef 556

Using defined 557

The Diminishing Role of the Preprocessor 557

#line 558

#pragma 559

The # and ## Preprocessor Operators 559

Predefined Macro Names 560

Final Thoughts 561

A C-Based I/O 563

C I/O Uses Streams 564

Understanding printf( ) and scanf( ) 565

printf( ) 565

scanf( ) 567

The C File System 572

fopen( ) 573

fputc( ) 574

fgetc( ) 574

feof( ) 575

fclose( ) 575

Using fopen( ), fgetc( ), fputc( ), and fclose( ) 575

ferror( ) and rewind( ) 576

fread( ) and fwrite( ) 577

Trang 16

fseek( ) and Random-Access I/O 578

fprintf( ) and fscanf( ) 579

Erasing Files 580

B Working with an Older C++ Compiler 581

Two Simple Changes 583

C The NET Managed Extensions to C++ 585

The NET Keyword Extensions 586

_ _abstract 586

_ _box 587

_ _delegate 587

_ _event 587

_ _finally 587

_ _gc 587

_ _identifier 587

_ _interface 587

_ _nogc 587

_ _pin 588

_ _property 588

_ _sealed 588

_ _try_cast 588

_ _typeof 588

_ _value 588

Preprocessor Extensions 588

The attribute Attribute 589

Compiling Managed C++ 589

Index 591

Trang 17

This page intentionally left blank

Trang 18

This book teaches you how to program in C++ — the most powerful computer language

in use today No previous programming experience is required The book starts withthe basics, covers the fundamentals, moves on to the core of the language, andconcludes with its more advanced features By the time you finish, you will be anaccomplished C++ programmer

C++ is your gateway to modern, object-oriented programming It is the preeminentlanguage for the development of high-performance software and is the choice ofprogrammers worldwide Simply put, to be a top-flight, professional programmertoday implies competency in C++

C++ is more than just a popular language C++ provides the conceptual substrata thatunderlie the design of several other languages, and much of modern computing It is

no accident that two other important languages, Java and C#, are descended fromC++ There is little in programming that has not been influenced by the syntax, style,and philosophy of C++

Because C++ was designed for professional programming, C++ is not the easiest

programming language to learn It is, however, the best programming language to

learn Once you have mastered C++, you will be able to write professional-quality,high-performance programs You will also be able to easily learn languages likeJava or C# because they share the same basic syntax and design as C++

What Is New in the Third Edition

In the time that has passed since the previous edition of this book, there have been

no changes to the C++ language There have, however, been big changes to thecomputing environment For example, Java became the dominant language for Webprogramming, the NET Framework was released, and C# was invented Through allthe changes of the past few years, one thing has remained constant: the staying

xvii

Trang 19

power of C++ C++ has been, is, and will remain the dominant language of “powerprogrammers” well into the forseeable future.

The overall structure and organization of the third edition is similar to the secondedition Most of the changes involve updating and expanding the coverage throughout

In some cases, additional details were added In other cases, the presentation of atopic was improved In still other situations, descriptions were modernized to reflectthe current programming environment Several new sections were also added

Two appendices were added One describes the extended keywords defined by Microsoftthat are used for creating managed code for the NET Framework The second explainshow to adapt the code in this book for use with an older, non-standard C++ compiler.Finally, all code examples were retested against the current crop of compilers, includingMicrosoft’s Visual Studio NET and Borland’s C++ Builder

What Version of C++

The material in this book describes Standard C++ This is the version of C++ defined

by the ANSI/ISO Standard for C++, and it is the one that is currently supported by allmajor compilers Therefore, using this book, you can be confident that what you learntoday will also apply tomorrow

How to Use This Book

The best way to learn any programming language, including C++, is by doing Therefore,after you have read through a section, try the sample programs Make sure that youunderstand why they do what they do before moving on You should also experimentwith the programs, changing one or two lines at a time and observing the results Themore you program, the better you become at programming

If You’re Using Windows

If your computer uses Windows and your goal is to write Windows-based programs, thenyou have chosen the right language to learn C++ is completely at home with Windowsprogramming However, none of the programs in this book use the Windows graphical userinterface (GUI) Instead, they are console-based programs that can be run under a Windowsconsole session, such as that provided by the Command Prompt window The reason forthis is easy to understand: GUI-based Windows programs are, by their nature, large andcomplex They also use many techniques not directly related to the C++ language.Thus, they are not well-suited for teaching a programming language However, you canstill use a Windows-based compiler to compile the programs in this book because thecompiler will automatically create a console session in which to execute your program.Once you have mastered C++, you will be able to apply your knowledge to Windowsprogramming In fact, Windows programming using C++ allows the use of classlibraries such as MFC or the newer NET Framework, which can greatly simplify thedevelopment of a Windows program

Don’t Forget: Code on the Web

Remember, the source code for all of the programs in this book is available free of charge

on the Web at http://www.osborne.com Downloading this code prevents you

from having to type in the examples

Trang 20

For Further Study

C++from the Ground Up is your gateway to the Herb Schildt series of programming

books Here are some others that you will find of interest

To learn more about C++, try

C++: The Complete Reference C++: A Beginner’s Guide Teach Yourself C++

STL Programming From the Ground Up C++ Programmer’s Reference

To learn about Java programming, we recommend the following:

Java 2: A Beginner’s Guide Java 2: The Complete Reference Java 2 Programmer’s Reference

To learn about C#, Herb offers these books:

C#: A Beginner’s Guide C#: The Complete Reference

To learn about Windows programming we suggest the following Schildt books:

Windows 98 Programming From the Ground Up Windows 2000 Programming From the Ground Up MFC Programming From the Ground Up

The Windows Programming Annotated Archives

If you want to learn about the C language, which is the foundation of all modernprogramming, then the following titles will be of interest

C: The Complete Reference Teach Yourself C

When you need solid answers, fast, turn to Herbert Schildt,

the recognized authority on programming.

Trang 21

This page intentionally left blank

Trang 22

CHAPTER 1 The Story of C++

1

Trang 23

C++ is the single most important language that any programmer can learn This

is a strong statement, but it is not an exaggeration C++ is the center of gravityaround which all of modern programming revolves Its syntax and design philosophydefine the essence of object-oriented programming Moreover, C++ charts the coursefor future language development For example, both Java and C# are directly descendedfrom C++ C++ is also the universal language of programming; it is the language inwhich programmers share ideas with one another To be a professional programmertoday implies competency in C++ It is that fundamental and that important C++ isthe gateway to all of modern programming

Before beginning your study of C++, it is important for you to know how C++ fits intothe historical context of computer languages Understanding the forces that drove itscreation, the design philosophy it represents, and the legacy that it inherits makes iteasier to appreciate the many innovative and unique features of C++ With this inmind, this chapter presents a brief history of the C++ programming language, its origins,its relationship to its predecessor (C), its uses, and the programming philosophies that

it supports It also puts C++ into perspective relative to other programming languages

The Origins of C++

The story of C++ begins with C The reason for this is simple: C++ is built upon thefoundation of C In fact, C++ is a superset of C (Indeed, all C++ compilers can also beused to compile C programs!) Specifically, C++ is an expanded and enhanced version

of C that embodies the philosophy of object-oriented programming (which is describedlater in this chapter) C++ also includes several other improvements to the C language,including an extended set of library routines However, much of the spirit and flavor

of C++ is inherited directly from C To fully understand and appreciate C++, you need

to understand the “how and why” behind C

The Creation of C

The C language shook the computer world Its impact should not be underestimatedbecause it fundamentally changed the way programming was approached and thoughtabout C is considered by many to be the first modern “programmer’s language.” Prior

to the invention of C, computer languages were generally designed either as academicexercises or by bureaucratic committees C is different C was designed, implemented,and developed by real, working programmers, and it reflected the way they approachedthe job of programming Its features were honed, tested, thought about, and rethought

by the people who actually used the language The result of this process was a languagethat programmers liked to use Indeed, C quickly attracted many followers who had

a near-religious zeal for it, and it found wide and rapid acceptance in the programmercommunity In short, C is a language designed by and for programmers

C was invented and first implemented by Dennis Ritchie on a DEC PDP-11 using theUNIX operating system C is the result of a development process that started with anolder language called BCPL, which was developed by Martin Richards BCPL influenced

a language called B, invented by Ken Thompson, which led to the development of

C in the 1970s

Trang 24

For many years, the de facto standard for C was the one supplied with the Unix

operating system and described in The C Programming Language, by Brian Kernighan

and Dennis Ritchie (Prentice-Hall, 1978) However, because no formal standard existed,there were discrepancies between different implementations of C To alter this situation,

a committee was established in the beginning of the summer of 1983 to work on thecreation of an ANSI (American National Standards Institute) standard that woulddefine—once and for all—the C language The final version of the standard was adopted

in December 1989, the first copies of which became available in early 1990 This version

of C is commonly referred to as C89, and it is the foundation upon which C++ is built.

NOTE: The C standard was updated in 1999 and this version of C is usually

referred to as C99 This version contains some new features, including a few borrowed

from C++, but, overall, it is compatible with the original C89 standard At the time ofthis writing, no widely available compiler supports C99 and it is still C89 that defineswhat is commonly thought of as the C language Furthermore, it is C89 that is the basisfor C++ It is possible that a future standard for C++ will include the features added

by C99, but they are not part of C++ at this time

It may seem hard to understand at first, but C is often called a “middle-level” computerlanguage As it is applied to C, middle-level does not have a negative connotation; itdoes not mean that C is less powerful, harder to use, or less developed than a “high-level”

language, or that it is as difficult to use as assembly language (Assembly language, or

assembler, as it is often called, is simply a symbolic representation of the actual machine

code that a computer can execute.) C is thought of as a middle-level language because

it combines elements of high-level languages, such as Pascal, Modula-2, or Visual Basic,with the functionality of assembler

From a theoretical point of view, a high-level language attempts to give the programmer everything he or she could possibly want, already built into the language A low-level

language provides nothing other than access to the actual machine instructions.

A middle-level language gives the programmer a concise set of tools and allows the

programmer to develop higher-level constructs on his or her own A middle-levellanguage offers the programmer built-in power, coupled with flexibility

Being a middle-level language, C allows you to manipulate bits, bytes, and addresses—the basic elements with which a computer functions Thus, C does not attempt tobuffer the hardware of the machine from your program to any significant extent Forexample, the size of an integer in C is directly related to the word size of the CPU Inmost high-level languages there are built-in statements for reading and writing diskfiles In C, all of these procedures are performed by calls to library routines and not bykeywords defined by the language This approach increases C’s flexibility

C allows—indeed, needs—the programmer to define routines for performing high-level

operations These routines are called functions, and they are very important to the C

language In fact, functions are the building blocks of both C and C++ You can easilytailor a library of functions to perform various tasks that are used by your program

In this sense, you can personalize C to fit your needs

Trang 25

There is another aspect of C that you must understand, because it is also important

to C++: C is a structured language The most distinguishing feature of a structured

language is that it uses blocks A block is a set of statements that are logically connected.

For example, imagine an IF statement that, if successful, will execute five discretestatements If these statements can be grouped together and referenced as an indivisibleunit, then they form a block

A structured language supports the concept of subroutines with local variables A

local variable is simply a variable that is known only to the subroutine in which it is

defined A structured language also supports several loop constructs, such as while,

do-while, and for The use of the goto statement, however, is either prohibited or

discouraged, and is not the common form of program control in the same way that

it is in traditional BASIC or FORTRAN A structured language allows you to indentstatements and does not require a strict field concept (as did early versions of FORTRAN).Finally, and perhaps most importantly, C is a language that stays out of the way Theunderlying philosophy of C is that the programmer, not the language, is in charge.Therefore, C will let you do virtually anything that you want, even if what you tell

it to do is unorthodox, highly unusual, or suspicious C gives you nearly completecontrol over the machine Of course, with this power comes considerable responsibility,which you, the programmer, must shoulder

Understanding the Need for C++

Given the preceding discussion of C, you might be wondering why C++ was invented.Since C is a successful and useful computer programming language, why was there

a need for something else? The answer is complexity Throughout the history ofprogramming, the increasing complexity of programs has driven the need for betterways to manage that complexity C++ is a response to that need To better understandthis correlation, consider the following

Approaches to programming have changed dramatically since the invention of thecomputer The primary reason for change has been to accommodate the increasingcomplexity of programs For example, when computers were first invented, programmingwas done by toggling in the binary machine instructions using the computer’s frontpanel As long as programs were just a few hundred instructions long, this approachworked As programs grew, assembly language was invented so that programmerscould deal with larger, increasingly complex programs by using symbolic representations

of the machine instructions As programs continued to grow, high-level languageswere developed to give programmers more tools with which to handle complexity.The first widespread language was, of course, FORTRAN While FORTRAN was a veryimpressive first step, it is hardly a language that encourages clear, easy-to-understandprograms The 1960s gave birth to structured programming This is the method ofprogramming supported by languages such as C With structured languages, it was,for the first time, possible to write moderately complex programs fairly easily However,even with structured programming methods, once a project reaches a certain size, itscomplexity exceeds what a programmer can manage By the late 1970s, many projectswere near or at this point To solve this problem, a new way to program began to

emerge This method is called object-oriented programming (OOP for short) Using OOP,

Trang 26

a programmer could handle larger programs The trouble was that C did not supportobject-oriented programming The desire for an object-oriented version of C ultimatelyled to the creation of C++.

In the final analysis, although C is one of the most liked and widely used professionalprogramming languages in the world, there comes a time when its ability to handlecomplexity reaches its limit The purpose of C++ is to allow this barrier to be brokenand to help the programmer comprehend and manage larger, more complex programs

C++ Is Born

In response to the need to manage greater complexity, C++ was born It was invented

by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey He initiallycalled the new language “C with Classes.” However, in 1983 the name was changed

to C++

C++ contains the entire C language As stated earlier, C is the foundation uponwhich C++ is built C++ includes all of C’s features, attributes, and benefits It alsoadheres to C’s philosophy that the programmer, not the language, is in charge Atthis point, it is critical to understand that the invention of C++ was not an attempt

to create a new programming language Instead, it was an enhancement to an alreadyhighly successful language

Most of the additions that Stroustrup made to C were designed to support object-orientedprogramming In essence, C++ is the object-oriented version of C By building uponthe foundation of C, Stroustrup provided a smooth migration path to OOP Instead

of having to learn an entirely new language, a C programmer needed to learn only

a few new features to reap the benefits of the object-oriented methodology

But C is not the only language that influenced C++ Stroustrup states that some ofits object-oriented features were inspired by another object-oriented language calledSimula67 Therefore, C++ represents the blending of two powerful programmingmethods

When creating C++, Stroustrup knew that it was important to maintain the originalspirit of C, including its efficiency, flexibility, and philosophy, while at the same timeadding support for object-oriented programming Happily, his goal was accomplished.C++ still provides the programmer with the freedom and control of C, coupled withthe power of objects

Although C++ was initially designed to aid in the management of very large programs,

it is in no way limited to this use In fact, the object-oriented attributes of C++ can beeffectively applied to virtually any programming task It is not uncommon to see C++used for projects such as compilers, editors, programmer tools, games, and networkingprograms Because C++ shares C’s efficiency, much high-performance systems software

is constructed using C++ Also, C++ is frequently the language of choice for Windowsprogramming

One important point to remember is this: Because C++ is a superset of C, once youcan program in C++, you can also program in C! Thus, you will actually be learningtwo programming languages at the same time, with the same effort that you woulduse to learn only one

1

Trang 27

The Evolution of C++

Since C++ was first invented, it has undergone three major revisions, with each revisionadding to and altering the language The first revision was in 1985 and the secondoccurred in 1990 The third revision occurred during the C++ standardization process

In the early 1990s, work began on a standard for C++ Towards that end, a joint ANSIand ISO (International Standards Organization) standardization committee was formed.The first draft of the proposed standard was created on January 25, 1994 In that draft,the ANSI/ISO C++ committee (of which I was a member) kept the features first defined

by Stroustrup and added some new ones as well But, in general, this initial draft reflectedthe state of C++ at the time

Soon after the completion of the first draft of the C++ standard, an event occurred thatcaused the standard to expand greatly: the creation of the Standard Template Library(STL) by Alexander Stepanov As you will learn, the STL is a set of generic routinesthat you can use to manipulate data It is both powerful and elegant But the STL isalso quite large Subsequent to the first draft, the committee voted to include the STL

in the specification for C++ The addition of the STL expanded the scope of C++ wellbeyond its original definition While important, the inclusion of the STL, amongother things, slowed the standardization of C++

It is fair to say that the standardization of C++ took far longer than any one hadexpected when it began In the process, many new features were added to thelanguage and many small changes were made In fact, the version of C++ defined

by the C++ committee is much larger and more complex than Stroustrup’s originaldesign The final draft was passed out of committee on November 14, 1997, and anANSI/ISO standard for C++ became a reality in 1998 This specification for C++ is

commonly referred to as Standard C++.

The material in this book describes Standard C++ This is the version of C++ supported

by all mainstream C++ compilers, including Microsoft’s Visual C++ and Borland’s C++Builder Therefore, the code and information in this book is fully applicable to allmodern C++ environments

What Is Object-Oriented Programming?

Since object-oriented programming was fundamental to the development of C++, it

is important to define precisely what object-oriented programming is Object-orientedprogramming has taken the best ideas of structured programming and has combinedthem with several powerful concepts that allow you to organize your programs moreeffectively In general, when programming in an object-oriented fashion, you decompose

a problem into its constituent parts Each component becomes a self-contained objectthat contains its own instructions and data related to that object Through this process,complexity is reduced and you can manage larger programs

All object-oriented programming languages have three things in common: encapsulation,polymorphism, and inheritance Although we will examine these concepts in detail later

in this book, let’s take a brief look at them now

Trang 28

As you probably know, all programs are composed of two fundamental elements:

program statements (code) and data Code is that part of a program that performs actions, and data is the information affected by those actions Encapsulation is a

programming mechanism that binds together code and the data it manipulates,and that keeps both safe from outside interference and misuse

In an object-oriented language, code and data may be bound together in such a way

that a self-contained black box is created Within the box are all necessary data and

code When code and data are linked together in this fashion, an object is created

In other words, an object is the device that supports encapsulation.

Within an object, the code, data, or both may be private to that object or public

Private code or data is known to, and accessible only by, another part of the object.

That is, private code or data may not be accessed by a piece of the program that exists

outside the object When code or data is public, other parts of your program may access

it, even though it is defined within an object Typically, the public parts of an objectare used to provide a controlled interface to the private elements of the object

Polymorphism

Polymorphism (from the Greek, meaning “many forms”) is the quality that allows one

interface to be used for a general class of actions The specific action is determined bythe exact nature of the situation A simple example of polymorphism is found in thesteering wheel of an automobile The steering wheel (i.e., the interface) is the same nomatter what type of actual steering mechanism is used That is, the steering wheel worksthe same whether your car has manual steering, power steering, or rack-and-pinionsteering Therefore, once you know how to operate the steering wheel, you can driveany type of car The same principle can also apply to programming For example, consider

a stack (which is a first-in, last-out list) You might have a program that requires threedifferent types of stacks One stack is used for integer values, one for floating-pointvalues, and one for characters In this case, the algorithm that implements each stack

is the same, even though the data being stored differs In a non-object-oriented language,you would be required to create three different sets of stack routines, calling each set

by a different name, with each set having its own interface However, because ofpolymorphism, in C++ you can create one general set of stack routines (one interface)that works for all three specific situations This way, once you know how to use onestack, you can use them all

More generally, the concept of polymorphism is often expressed by the phrase

“one interface, multiple methods.” This means that it is possible to design a genericinterface to a group of related activities Polymorphism helps reduce complexity byallowing the same interface to be used to specify a general class of action It is the

compiler’s job to select the specific action (i.e., method) as it applies to each situation.

You, the programmer, don’t need to do this selection manually You need onlyremember and utilize the general interface

The first object-oriented programming languages were interpreters, so polymorphismwas, of course, supported at run time However, C++ is a compiled language Therefore,

in C++, both run-time and compile-time polymorphism are supported

1

Trang 29

Inheritance is the process by which one object can acquire the properties of another

object The reason this is important is that it supports the concept of hierarchicalclassification If you think about it, most knowledge is made manageable byhierarchical (i.e., top-down) classifications For example, a Red Delicious apple is part

of the classification apple, which in turn is part of the fruit class, which is under the larger class food That is, the food class possesses certain qualities (edible, nutritious, etc.) that also apply, logically, to its fruit subclass In addition to these qualities, the

fruit class has specific characteristics (juicy, sweet, etc.) that distinguish it from other

food The apple class defines those qualities specific to an apple (grows on trees, not

tropical, etc.) A Red Delicious apple would, in turn, inherit all the qualities of allpreceding classes, and would define only those qualities that make it unique

Without the use of hierarchies, each object would have to explicitly define all ofits characteristics However, using inheritance, an object needs to define only thosequalities that make it unique within its class It can inherit its general attributes fromits parent Thus, it is the inheritance mechanism that makes it possible for one object

to be a specific instance of a more general case

C++ Implements OOP

As you will see as you progress through this book, many of the features of C++ exist

to provide support for encapsulation, polymorphism, and inheritance Remember,however, that you can use C++ to write any type of program, using any type ofapproach The fact that C++ supports object-oriented programming does not meanthat you can only write object-oriented programs As with its predecessor, C, one ofC++’s strongest advantages is its flexibility

How C++ Relates to Java and C#

As most readers will know, there are two other computer languages that are having astrong impact on programming: Java and C# Java was developed by Sun Microsystemsand C# was created by Microsoft Because there is sometimes confusion about howthese two languages relate to C++, a brief discussion of their relationship is in order.C++ is the parent for both Java and C# Although Java and C# added, removed, andmodified various features, in total the syntax for all three languages is nearly identical.Furthermore, the object model used by C++ is similar to the ones used by Java and C#.Finally, the overall “look and feel” of these languages is very similar This means thatonce you know C++, you can easily learn Java or C# This is one reason that Java andC# borrowed C++’s syntax and object model; it facilitated their rapid adoption bylegions of experienced C++ programmers The reverse case is also true If you knowJava or C#, learning C++ is easy

The main difference between C++, Java, and C# is the type of computing environmentfor which each is designed C++ was created to produce high-performance programsfor a specific type of CPU and operating system For example, if you want to write

a high-performance program that runs on an Intel Pentium under the Windowsoperating system, then C++ is the best language to use

Trang 30

Java and C# were developed in response to the unique programming needs ofthe highly distributed networked environment that typifies much of contemporarycomputing Java was designed to enable the creation of cross-platform portable codefor the Internet Using Java, it is possible to write a program that runs in a wide variety

of environments, on a wide range of operating systems and CPUs Thus, a Java programcan move about freely on the Internet C# was designed for Microsoft’s NET Framework,which supports mixed-language, component-based code that works in a networkedenvironment

Although both Java and C# enable the creation of portable code that works in ahighly distributed environment, the price one pays for this portability is efficiency.Java programs execute slower than do C++ programs The same is true for C# Thus,

if you want to create high-performance software, use C++ If you need to createhighly portable software, use Java or C#

One final point: C++, Java, and C# are designed to solve different sets of problems

It is not an issue of which language is best in and of itself Rather, it is a question ofwhich language is right for the job at hand

1

Trang 31

This page intentionally left blank

Trang 32

CHAPTER 2

An Overview

of C++

11

Trang 33

One of the hardest things about learning a programming language is the fact that

no element exists in isolation Rather, the components of the language worktogether It is this interrelatedness that makes it difficult to discuss one aspect of C++without involving another To help overcome this problem, this chapter provides abrief overview of several core C++ features, including the general form of a C++ program,some simple control statements, variables, and operators It does not go into toomany details, but rather concentrates on the general concepts common to all C++programs Most of the topics presented here are examined more closely in later chapters.Since learning is best accomplished by doing, it is recommended that you work throughthe examples using your computer

Your First C++ Program

Before getting into any theory, let’s look at a simple C++ program We will start byentering, compiling, and running the following program

/* Program #1 - A first C++ program.

Enter this program, then compile and run it.

cout << "This is my first C++ program.";

return 0;

}

You will follow these steps

1 Enter the program

2 Compile the program

3 Execute the program

Before beginning, it is necessary to define two terms The first is source code Source

code is the version of your program that humans can read The preceding listing is an

example of source code The executable version of your program is called object code or

executable code Object code is created by the compiler when it compiles your program.

Entering the Program

The programs shown in this book are available from Osborne’s Web site:

www.osborne.com However, if you want to enter the programs by hand,

you are free to do so Typing in the programs yourself often helps you rememberthe key concepts If you choose to enter a program by hand, you must use a text

Source code is

the form of your

program that you

Trang 34

.cpp Thus, you can call a C++ program file by any name, but it should use the cpp

extension For this example, call the source file MyProg.cpp so that you can follow

along For most of the other programs in this book, simply use a name of your ownchoosing

Compiling the Program

How you will compile MyProg.cpp depends upon your compiler, and what options

you are using Furthermore, many compilers, such as Microsoft’s Visual C++ andBorland’s C++ Builder, provide two different ways for compiling a program: thecommand line compiler and the Integrated Development Environment (IDE) Thus,

it is not possible to give generalized instructions for compiling a C++ program thatwill work for all compilers You must consult your compiler’s instructions

The preceding paragraph not withstanding, two of the most popular compilers areVisual C++ and C++ Builder For the benefit of readers using one of these compilers,brief compilation instructions are provided here For both Visual C++ or C++ Builder,the easiest way to compile and run the programs in this book is to the use thecommand-line compilers offered by these environments, and that is the methoddescribed

To compile MyProg.cpp using Visual C++, you will use this command line.

C:\ >cl -GX MyProg.cpp

The –GX option enhances compilation To use the Visual C++ command-linecompiler, you must first execute the batch file VCVARS32.BAT, which is provided

by Visual C++ (You will want to consult your Visual C++ documentation for details.)

To compile MyProg.cpp using C++ Builder, use this command line.

be using an older C++ compiler that predates the ANSI/ISO standard for C++ If this

is the case, refer to Appendix B for instructions on using an older compiler

Trang 35

Run the Program

After a C++ program has been compiled, it is ready to be run Since the output from aC++ compiler is executable object code, to run the program, simply enter its name at

the command prompt For example, to run MyProg.exe use this command line:

C:\ >MyProg

When run, the program displays the following output

This is my first C++ program.

If you are using an Integrated Development Environment, then you can run a program

by selecting Run from a menu Consult the instructions for your specific compiler Asmentioned earlier, for the programs in this book, it is usually easier to compile andrun from the command line

One last point: The programs in this book are console-based, not window-based.That is, they run in a Command Prompt session C++ is completely at home withWindows programming Indeed, it is the most commonly used language for Windowsdevelopment However, none of the programs in this book use the Windows GraphicUser Interface (GUI) The reason for this is easy to understand: Windows is a complicatedenvironment to write programs for, involving many side issues unrelated to the C++language In contrast, console-based programs are much shorter and are the type ofprograms normally used to teach programming Once you have mastered C++, youwill be able to apply your knowledge to Windows programming with no trouble

A Line-by-Line Explanation

Now that you have successfully compiled and run the first sample program it is time

to understand how it works Towards this end, we will examine the program line byline The program begins with the lines

/* Program #1 - A first C++ program.

Enter this program, then compile and run it.

*/

This is a comment Like most other programming languages, C++ lets you enter a remark

into a program’s source code The contents of a comment are ignored by the compiler.The purpose of a comment is to describe or explain the operation of a program toanyone reading its source code In the case of this comment, it identifies the program

In more complex programs, you will use comments to help explain what each feature

of the program is for and how it goes about doing its work In other words, you canuse comments to provide a “play-by-play” description of what your program does

In C++, there are two types of comments The one you’ve just seen is called a multiline

comment This type of comment begins with a /* (a slash followed by an asterisk) It

ends only when a */ is encountered Anything between these two comment symbols

A comment is

a remark that

is embedded in

your program.

Trang 36

is completely ignored by the compiler Multiline comments may be one or more lineslong The second type of comment is found a little further on in the program; we’ll bediscussing it shortly.

The next line of code looks like this:

#include <iostream>

The C++ language defines several headers, which contain information that is either

necessary or useful to your program For this program, the header <iostream> is

needed (It is used to support the C++ I/O system.) This header is provided with your

compiler A header is included in your program by using the #include directive Later

in this book, you will learn more about headers and why they are important

The next line in the program is

using namespace std;

This tells the compiler to use the std namespace Namespaces are a relatively recent

addition to C++ Although namespaces are discussed in detail later in this book, here

is a brief description A namespace creates a declarative region in which various program

elements can be placed Elements declared in one namespace are separate from elementsdeclared in another Namespaces help in the organization of large programs The

using statement informs the compiler that you want to use the std namespace.

This is the namespace in which the entire Standard C++ library is declared By

using the std namespace, you simplify access to the standard library.

The next line in the program is

// main() is where program execution begins.

This line shows you the second type of comment available in C++: the single-line

comment Single-line comments begin with // and stop at the end of the line.

Typically, C++ programmers use multiline comments when writing larger, moredetailed commentaries, and they use single-line comments when short remarksare needed However, this is a matter of personal style

The next line, as the preceding comment indicates, is where program executionbegins:

int main()

All C++ programs are composed of one or more functions (Loosely speaking, a function

is a subroutine.) Every C++ function must have a name, and the only function that

any C++ program must include is the one shown here, called main( ) The main( )

function is where program execution begins and (most commonly) ends (Technically

speaking, a C++ program begins with a call to main( ) and, in most cases, ends when

main( ) returns.) The opening curly brace on the line that follows main( ) marks the

start of the main( ) function’s code The int that precedes main( ) specifies the type

2

main( ) is where

a C++ program

begins execution.

Trang 37

of data returned by main( ) As you will learn, C++ supports several built-in data

types and int is one of them It stands for integer.

The next line in the program is

cout << "This is my first C++ program.";

This is a console output statement It causes the message This is my first C++

program to be displayed on the screen It accomplishes this by using the output

operator << The << operator causes whatever expression is on its right side to be output to the device specified on its left side cout is a predefined identifier that

stands for console output, which (most generally) refers to the computer’s screen.

Thus, this statement causes the message to be output to the screen Notice that thisstatement ends with a semicolon In fact, all C++ statements end with a semicolon

The message "This is my first C++ program." is a string In C++, a string is a sequence

of characters enclosed between double quotes As you will see, strings are usedfrequently in C++

The next line in the program is

return 0;

This line terminates main( ) and causes it to return the value 0 to the calling process

(which is typically the operating system) For most operating systems, a return value

of 0 signifies that the program is terminating normally Other values indicate that the

program is terminating because of some error return is one of C++’s keywords, and

it is used to return a value from a function All of your programs should return 0 whenthey terminate normally (that is, without error)

The closing curly brace at the end of the program formally concludes the program.Although the brace is not actually part of the object code of the program, conceptually

you can think of a C++ program ending when the closing curly brace of main( ) is executed In fact, if the return statement were not part of this sample program, the

program would automatically end when the closing curly brace was encountered

Handling Syntax Errors

As you may know from your previous programming experience, it is quite easy

to accidentally type something incorrectly when entering code into your computer.Fortunately, if you enter something incorrectly into your program, the compiler will

report a syntax error message when it tries to compile it Most C++ compilers attempt

to make sense out of your source code no matter what you have written For this reason,the error that is reported may not always reflect the actual cause of the problem In thepreceding program, for example, an accidental omission of the opening curly brace

after main( ) will cause some compilers to report the cout statement as the source

of a syntax error Therefore, when you receive a syntax error message, be prepared

to look at the two or three lines of code that precede the point at which the error

is flagged

Trang 38

Many C++ compilers report not only actual errors, but also warnings The C++ languagewas designed to be very forgiving, and to allow virtually anything that is syntacticallycorrect to be compiled However, some things, even though syntactically correct, aresuspicious When the compiler encounters one of these situations, it prints a warning.You, as the programmer, then decide whether its suspicions are justified Frankly,some compilers are a bit too helpful and flag warnings on perfectly correct C++

statements There are also compilers that allow you to turn on various options thatreport information about your program that you might like to know Sometimesthis information is reported in the form of a warning message even though there

is nothing to be "warned" about The programs in this book are in compliance withStandard C++, and when entered correctly, they will not generate any troublesomewarning messages

TIP: Most C++ compilers offer several levels of error (and warning) reporting

Generally, you can select the specific type of error reporting that you want For example,most compilers offer options that report such things as inefficient constructs or theuse of obsolete features For the examples in this book, you will want to use yourcompiler's default (or "normal") error reporting However, you should examineyour compiler's documentation to see what options you have at your disposal Manycompilers have sophisticated features that can help you spot subtle errors before theybecome big problems Understanding your compiler's error reporting system is worththe time and effort that you spend

A Second Simple Program

Perhaps no other construct is as important to a programming language as the assignment

of a value to a variable A variable is a named memory location that may be assigned

a value Further, the value of a variable can be changed one or more times during theexecution of a program That is, the content of a variable is changeable, not fixed

The following program creates a variable called x, gives it the value 1023, and then displays the message This program prints the value of x: 1023 on the screen.

// Program #2 - Using a variable

#include <iostream>

using namespace std;

int main() {

int x; // this declares a variable

x = 1023; // this assigns 1023 to x cout << "This program prints the value of x: ";

cout << x; // This displays 1023 return 0;

}

Trang 39

This program introduces two new concepts First, the statement

int x; // this declares a variable

declares a variable called x of type integer In C++, all variables must be declared

before they are used Further, the type of values that the variable can hold must also

be specified This is called the type of the variable In this case, x may hold integer

values These are whole-number values whose range will be at least –32,768 to 32,767

In C++, to declare a variable to be of type integer, precede its name with the keyword

int Later, you will see that C++ supports a wide variety of built-in variable types.

(You can create your own data types, too.)The second new feature is found in the next line of code:

x = 1023; // this assigns 1023 to x

As the comment suggests, this assigns the value 1023 to x In C++, the assignment

operator is the single equal sign It copies the value on its right side into the variable

on its left After the assignment, the variable x will contain the number 1023.

The two cout statements display the output generated by the program Notice how the following statement is used to display the value of x:

cout << x; // This displays 1023

In general, if you want to display the value of a variable, simply put it on the right

side of << in a cout statement In this specific case, because x contains the number

1023, it is this number that is displayed on the screen Before moving on, you might

want to try giving x other values and watching the results.

A More Practical Example

Your first two sample programs, while illustrating several important features of theC++ language, are not very useful The next sample program actually performs ameaningful task: It converts gallons to liters It also shows how to input information

// This program converts gallons to liters.

#include <iostream>

using namespace std;

int main() {

int gallons, liters;

cout << "Enter number of gallons: ";

cin >> gallons; // this inputs from the user liters = gallons * 4; // convert to liters

Trang 40

cout << "Liters: " << liters;

return 0;

}

This program first displays a prompting message on the screen, and then waits for you

to enter a whole number amount of gallons (Remember, integer types cannot havefractional components.) The program then displays the approximate liter equivalent.There are actually 3.7854 liters in a gallon, but since integers are used in this example,the conversion is rounded to 4 liters per gallon For example, if you enter 1 gallon, theprogram responds with the metric equivalent of 4 liters

The first new thing you see in this program is that two variables, gallons and liters, are declared following the int keyword, in the form of a comma-separated list In

general, you can declare any number of variables of the same type by separating them

with commas (As an alternative, the program could have used multiple int statements

to accomplish the same thing.)The function uses this statement to actually input a value entered by the user:

cin >> gallons; // this inputs from the user

cin is another predefined identifier that is provided with your C++ compiler cin

stands for console input (which generally means input from the keyboard) The input

operator is the >> symbol The value entered by the user (which must be an integer,

in this case) is put into the variable that is on the right side of the >> (in this case,

gallons).

There is one more new thing in this program Examine this line:

cout << "Liters: " << liters;

It uses two output operators within the same output statement Specifically, it outputs

the string "Liters: " followed by the value of liters In general, you can chain together

as many output operations as you like within one output statement Just use a separate

<< for each item.

A New Data Type

Although the gallons-to-liters program is fine for rough approximations, because

it uses integers, it leaves something to be desired when a more accurate answer isneeded As stated, integer data types cannot represent any fractional value If youneed fractions, then you must use a floating-point data type One of these is called

double, which represents double-precision floating-point Data of this type will typically

be in the range 1.7E–308 to 1.7E+308 Operations on floating-point numbers preserveany fractional part of the outcome and, hence, provide a more accurate conversion.The following version of the conversion program uses floating-point values:

/* This program converts gallons to liters using floating point numbers */

Ngày đăng: 19/03/2014, 14:09

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w