ĐẠi hỌc QuỐc Gia ThÀnh PhỐ hỒ ChÍ Minh TrƯỜng

Embed Size (px)

Citation preview

I HC QUC GIA THNH PH H CH MINH TRNG I HC KHOA HC T NHIN TPHCM KHOA: CNG NGH THNG TIN LP 06C2 ****** BI DCH TEACH YOURSELF C++ THIRD EDITION GVHD: MN : Th.s.NGUYN TN TRN MINH KHANG PP LP TRNH HNG I TNG NHM THC HIN: 8BIT 1.Trnh Vn Long 2.on Minh Bo Long 3.H An Phong 4.Trn Quang long 5.Nguyn Thnh Long 6.Nguyn Vn Nm 7. Trng Long 8. Dng Hunh ngha 0612229 0612231 0612330 0612227 0612223 0612326 0612232 0612285 1

LI M U *** c s gip , hng dn ca thy cc thnh vin ca nhm 8BIT cng nhau tho lun,nghin cu dch sch Teach Yourselt C++, Third Editon ngha l T Hc C++, n bn 3 ca tc gi Herbert Schildt. y l mt cun sch rt hay, d hiu v rt hu ch cho vic hc tp b mn ny cng nh cc b mn sau ny . c bit l nhng ai mi bc vo con ng tr thnh lp trinh vin quc t hay mt chuyn vin phn mm, Phng Php Lp Trnh Hng i Tng n nh hng cho ngi lp trnh mt cch tng quan v lp trnh. i vi nhng sinh vin trong giai on i cng th n i xuyn sut bn nm hc. Cc thnh vin ca nhm c gng nhng cng khng trnh khi nhng sai st do thiu kinh nghim dch sch, mong thy v qu v c gi thng cm. cho cun sch c hon thin rt mong s gp ca cc c gi. Nhm 8BIT xin chn thnh cm n. Nhm 8BIT 2

MC LC CHNG 1................................................................................. .......................................6 AN OVERVIEW OF C++ - TNG QUAN V C+ +...................................................6 1.1. WHAT IS OBJECT-ORIENTED PROGRAMMING ?- LP TRNH HNG I TNG L G ?.............................................................................. .....................10 1.2. TWO VERSIONS OF C++ - HAI PHIN BN CA C+ +...................................18 1.3. C++ CONSOLE I / O - BN GIAO TIP NHP/XUT C++..........................28 1.4. C++ COMMENTS LI CH GII TRONG C++.............................................38 1.5. CLASSSES: A FIRST LOOK LP : CI NHN U TIN ............................40 1.6. SOME DIFFERENCE BETWEENCE AND C++ - MT S KHC BIT GIA C V C+ +................................................................................. .....................................50 1.7. INTRODUCING FUNCTION OVERLOADING DN NHP S NP CHNG HM:.............................................................................. ................................58 1.8. C++ KEYWORDS T KHA TRONG C+ + ...................................................66 CHNG 2................................................................................. .....................................69 Gii Thiu Lp (Introducing Classes)........................................................................69 2.2. CONSTRUCTORS THAT TAKE PARAMETERS - THAM S CA HM TO .............................................................................. ..........................................................84 2.3. INTRODUCING INHERITANCE - GII THIU TNH K THA:..................96 1.4. OBJECT POINTERS CON TR I TNG:...............................................109 1.6. IN-LINE FUNCTION - HM NI TUYN:.....................................................126 1.7. AUTOMATIC IN-LINING - HM NI TUYN T NG:...........................132 CHAPTER 3................................................................................. ..................................141 A CLOSER LOOK AT CLASSES - Xt K Hn V Lp.........................................141 1.1. Assigning Objects - Gn i tng:......................................................................143 1.2. PASSING OBJECTS TO FUNCTIONS Truyn cc i tng cho hm:.........155 1.3. RETURNING OBJECT FROM FUNCTIONS Tr v i tng cho hm:......167 CHNG 4................................................................................. ...................................194 ARRAYS, POITERS, AND REFERENCES - Mng, con tr v tham chiu...........194 1.1. ARRAYS OF OBJECTS - MNG CC I TNG......................................197 1.2. USING POINTERS TO OBJECTS S dng con tr i tng:.......................206 1.4. USING NEW AND DELETE - Cch dng ton t new v delete:......................215 1.5. MORE ABOUT NEW AND DELETE - M Rng ca new v delete:................220 1.6. REFERENCES - Tham chiu:............................................................................ ..229 1.7. PASSING REFERENCES TO OBJECTS Truyn tham chiu cho i tng:..237 1.8. RETURNING REFERENCES - Tr v tham chiu:............................................243 1.9. INDEPENDENT REFERENCES AND RESTRICTIONS - THAM CHIU C LP V NHNG HN CH :............................................................................. ......250 CHAPTER 5................................................................................. ..................................257 FUNCTION OVERLOADING Np chng hm.....................................................257 5.1. OVERLOADING CONSTRUCTOR FUNCTIONS - QA TI CC HM TO: ............................................................................. .........................................................260 5.2. CREATING AND USING A COPY CONSTRUCTOR - TO V S DNG HM TO BN SAO:..............................................................................

.................270 5.3. THE OVERLOAD ANACHRONISM - S Li Thi Ca T kha Overload:...288 3

5.4. USING DEFAULT ARGUMENTS - S dng cc i s mc nh:...................289 5.5. OVERLOADING AND AMBIGUITY - S QU TI V TNH KHNG XC NH:............................................................................. .............................................302 5.6. FINDING THE ADDRESS OF AN OVERLOADED FUNCTION - TM A CH CA MT HM QU TI:.............................................................................. .309 CHNG 6................................................................................. ...................................320 INTRODUCING OPERATOR OVERLOADING ....................................................320 GII THIU V NP CHNG TON T...............................................................320 THE BASICS OF OPERATOR OVERLOADING - C S CA QU TI TON T................................................................................ ................................................323 OVERLOADING BINARY OPERATORS QU TI TON T NH NGUYN.326 OVERLOADING THE RELATIONAL AND LOGICAL OPERATORS QU TI CC TON T QUAN H V LUN L...............................................................339 OVERLOADING A UNARY OPERATOR - QU TI TON T N NGUYN ........................................................................... ...........................................................343 6.5. USING FRIEND OPERATOR FUNCTION - S DNG HM TON T FRIEND............................................................................ ...........................................350 6.6. A CLOSER LOOK AT THE ASSIGNMENT OPERATOR - Mt Ci Nhn V Ton T Gn............................................................................... .................................362 6.7. OVERLOADING THE [ ] SUBSCRIPT OPERATOR QU TI CA TON T [ ] CH S DI ............................................................................. ....................368 CHNG 7 ................................................................................ ...................................384 INHERITANCE - TNH K THA............................................................................38 4 1.1. BASE CLASS ACCESS CONTROL IU KHIN TRUY CP LP C S ............................................................................... .......................................................390 1.2. USING PROTECTED MEMBERS - S DNG CC THNH VIN C BO V................................................................................ .......................................404 1.3. CONSTRUCTORS, DESTRUCTORS, AND INHERITANCE - HM TO, HM HY V TNH K THA.............................................................................. .413 1.4. MULTIPLE INHERITANCE - TNH A K THA ......................................432 1.5. VIRTUAL BASE CLASSES - CC LP C S O......................................448 CHNG 8................................................................................. ...................................468 INTRODUCING THE C++ I/O SYSTEM - DN NHP H THNG NHP/XUT C+ +................................................................................. .................................................468 1.1. SOME C++ I/O BASICS - C s Nhp/Xut C++..............................................474 1.2. FORMATTED I/O - Nhp/Xut C nh Dng...................................................478 1.3. USING WIDTH( ), PRECISION( ), AND FILL( ) S DNG HM WIDTH(), PRECISION( ), V FILL( ):.......................................................................... .............493 1.4. USING I/O MANIPULATORS S DNG B THAO TC NHP XUT...499 1.5. CREATING YOUR OWN INSERTERS TO B CHN VO:.....................506 1.6. CREATING EXTRACTORS TO B CHIT:...............................................517 CHAPTER

9................................................................................. ..................................526 ADVANCE C++ I/O NHP XUT NNG CAO CA C+ +...................................526 9.1. CREATING YOUR OWN MANIPULATORS TO CC THAO TC RING ............................................................................ ..........................................................529 9.2. FILE I/O BASICS NHP XUT FILE C BN............................................536 4

9.3. UNFORMATTED, BINARY I/O - NHP XUT NHIPHN KHNG INH DANG.............................................................................. ............................................548 9.4. MORE UNFORMATTED I/O FUNCTIONS - THM MT S HM NHP/XUT KHNG C NH DNG...........................................................559 9.5. RANDOM ACCESS - TRUY XUT NGU NHIN.........................................566 9.6. CHECKING THE I/O STATUS - KIM TRA TRNG THI I/O......................572 9.7. CUSTOMIZED I/O AND FILES - FILE V I/O THEO YU CU..................578 CHAPTER 10................................................................................ .................................585 VIRTUAL FUNCTIONS - HAM AO........................................................................585 10.2. INTRODUCTION TO VIRTUAL FUNCTIONS TNG QUAN V HM O ............................................................................... .......................................................591 10.3. MORE ABOUT VIRTUAL FUNCTIONS - NOI THM VHAM AO..........605 10.4. APPLYING POLYMORPHISM AP DUNG A HINH.................................612 CHAPTER 11................................................................................ .................................628 TEMPLATES AND EXCEPTION HANDLING - NHNG BIU MU V TRNH IU KHIN BIT L................................................................................ ................628 11.1. GENERIC FUNCTIONS NHNG HM TNG QUT...............................630 11.2. GENERIC CLASSES LP TNG QUT......................................................641 11.3. EXCEPTION HANDLING- IU KHIN NGOI L...................................653 11.4. MORE ABOUT EXCEPTION HANDLING - TRNH BY THM V IU KHIN NGOI L................................................................................ .....................665 11.5. HANDLING EXCEPTIONS THROWN - S DNG NHNG NGOI L C NM............................................................................... .................................679 CHAPTER 12................................................................................ .................................689 RUN-TIME TYPE IDENTIFICATION AND THE CASTING OPERATORS KIU THI GIAN THC V TON T P KHUN............................................689 13.1. UDERSTANDING RUN-TIME TYPE IDENTIFICATION (RTTI) - TM HIU V S NHN DNG THI GIAN THC ..............................................................692 1.2. USING DYNAMIC_CAST S DNG DYNAMIC_CAST............................714 1.3. USING CONST_CAST, REINTERPRET_CAST, AND STATIC_CAST - CCH DNG CONST_CAST, REINTEPRET_CAST V STATIC_CAST.........................727 CHAPTER 13 ............................................................................... .................................737 NAMESPACES, CONVERSION FUNCTIONS, AND MISCELLANEOUS TOPICS - NAMESPACES, CC HM CHUYN I V CC CH KHC NHAU.737 13.1. NAMESPACES........................................................................ ..........................739 13.2. CREATING A CONVERSION FUNCTION TO MT HM CHUYN I .............................................................................. ........................................................756 13.3. STATIC CLASS AND MEMBERS LP TNH V CC THNH PHN...762 13.4. CONST MEMBER FUNCTIONS AND MUTABLE - HM THNH PHN KHNG I V C TH THAY I.....................................................................773 13.5. A FINAL LOOK AT CONSTRUCTORS - CI NHN CUI CNG V HM .............................................................................. ........................................................779 13.6. USING LINKAGE SPECIFIERS AND THE ASM KEYWORD......................786 13.7. ARRAY-BASE I/O MNG C S NHP/XUT......................................791 CHAPTER 14................................................................................ .................................800 INTRODUCING THE STANDARD TEMPLATE LIBRARY

GII THIU V 5

TH VIN GIAO DIN CHUN............................................................................. ..800 14.1. AN OVERVIEW OF THE STANDARD TEMPLATE LIBRARY TNG QUAN V TH VIN GIAO DIN CHUN...........................................................804 THE CONTAINER CLASSES LP CONTAINER.................................................809 14.3.VECTORS...................................................................... ......................................811 LISTS - DANH SCH.............................................................................. ..................823 14.4.MAPS - BAN :............................................................................... ................836 14.5.ALGORITHMS - Nhng thut giai.....................................................................846 14.6.THE STRING CLASS - Lp Chui....................................................................857 CHNG 1 AN OVERVIEW OF C++ - TNG QUAN V C++ Chapter object : 1.1. WHAT IS OBJECT-ORIENTED PROGRAMMING ?. Lp Trnh Hng i Tng L G ? 1.2. TWO VERSIONS OF C++. Hai Phin Bn C++ 1.3. C++ COMMENTS I/O Nhp / Xut C++ 1.4. C++ COMMENTS. Li Nhn Xt C++ 1.5. CLASSES: A FIRST LOOK. 6

LP : Ci Nhn u Tin. 1.6. SOME DIFFERENCE BETWEEN C AND C++. Mt S Khc Bit Gia C v C++. 1.7. INTRODUCING FUNCTION OVERLOADING. Dn Nhp S Qu Ti Hm. 1.8. C++ KEYWORDS SHILLS CHECK. Cc T Kha Trong C++. C++ is an enhanced version of C language. C++ includes everything that is part of C and adds support for object-oriented programming (OOP for short). In addition to, C++ contains many improvements and features that simply make it a better C, independent of object-oriented programming. With very few, very minor exceptions, C++ is a superset of C. While everything that you know about the C language is fully applicable to C++, understanding its enhanced features will still require a significant investment of time and effort on your part. However, the rewards of programming in C++ will more than justify the effort you put forth. C++ l mt phin bn ca ngn ng C. C++ bao gm nhng phn c trong C v thm vo l s h tr cho Lp trnh hng i tng (vit tt l OOP). Cng thm vo , C++ cn cha nhng ci tin v nhng ci tin m n gin nhng to ra mt phin bn C tt hn, khng ph thuc vo phng php lp trnh hng i tng. Vi rt t ring bit, C++ c th xem l tp cha ca C. Trong khi nhng g bn bit v C th hon ton c th thc hin trong C++, th vic hiu r nhng tnh nng ca C++ cng i hi mt s u t thch ng v thi gian cng nh n lc ca chnh bn thn bn. Tuy nhin, phn thng cho vic lp trnh bng C++ l s ngy cng chng minh c nng lc ca bn thn bn hn vi nhng g bn th hin. The purpose of this chapter is to introduce you to several of the most important features of C++. As you know, the emplements of a computer language do not exist in a void, separate from one another. Instead, they work together to form the complete language. This interrelatedness is especially pronounced in C++. In fact, it is difficult to discuss one aspect of 7

C++ in isolation because the features of C++ are highly integrated. To help overcome this problem, this chapter provides a brief overview of several C++ features. This overview will enable you to understand the examples discussed later in this book. Keep in mind that most topics will be more thoroughly explored in later chapters. Mc tiu ca chng ny l gii thiu cho bn 1 s tnh nng quan trng nht ca C++. Nh bn bit , nhng thnh phn ca ngn ng my tnh th khng cng tn ti trong 1 khong khng, m tch bit vi nhng ci khc, thay v lm vic cng nhau to thnh mt ngn ng hon chnh. Mi tng quan ny c c bit pht biu trong C++. S tht l rt kh tho lun v mt din mo ca C++ trong s c lp bi v nhng tnh nng ca C++ c tch hp cao . gip vt qua vn ny, chng ny cung cp mt ci nhn ngn gn v mt s tnh nng ca C++. Ci nhn tng quan ny s gip bn hiu hn v nhng th d m chng ta s tho lun phn sau cun sch. Hy ghi nh tt c nhng mc chng s gip bn hiu thu o nhng chng tip theo. Since C++ was invented to support object-oriented programming this chapter begins with a decriptions of OOP. As you will see, many features of C++ are related to OOP in one way or another. In fact, the theory of OOP permeates C++. However, it is important to understand that C++ can be used to write programs that are and are not object oriented. How you use C+ + is completely up to you. V C++ c thit k ra h tr cho vic lp trnh hng i tng, nn chng ny chng ta bt u vi vic m t v lp trnh hng i tng (OOP). Ri bn s thy rng nhng tnh nng khc ca C++ cng lien quan ti OOP bng cch ny hay cch khc. S tht l l thuyt v lp trnh hng i tng c tri dn trong C++. Tuy nhin, phi hiu rng vic dng C++ vit chng trnh th c hoc khng c hng i tng. Vic s dng C++ nh th no l hon ton ph thuc vo bn. At the time of this writing, the standardization of C++ is being finalized. For this reason, this chapter describes some important differences between versions of C++ that have been in common use during the past several years and the new Standard C++. Since this book teaches Standard C++, this material is especially important if you are using an older compiler. Vo thi im vit cun sch ny th vic chun ha C++ ang c hon tt. V l do chng ny s m t nhng s khc bit quan trng gia hai phin bn ca C++ m tng c dung ph bin trong nhng nm 8

trc y v tiu chun mi trong C++. V cun sch ny dy v Tiu chun C++, nn ti liu ny s c bit quan trng nu bn s dng nhng trnh bin dch c. In addition to introducing several important C++ features, this chapter also discusses some differences between C and C++ programming styles. There are several aspects of C++ that allow greater flexibility in the way that you are write programs. While some of these features have little or nothing to do with objectoriented programming, they are found in most C++ programs, so it is appropriate to discuss them early in this book. Thm vo vic gii thiu mt s tnh nng quan trng trong C++, chng ny cng tho lun v nhng khc bit gia hai phong cch lp trnh C v C++. y c vi yu t ca C++ cho php n c tnh linh ng hn trong vic vit chng trnh. Trong khi nhng yu t ny th rt t hoc khng c lp trnh hng i tng th n c tm thy hu nh y trong nhng chng trnh ca C++, v th s tht tha ng nu tho lun v chng trong khi u quyn sch ny. Before you begin, a few general comments about the nature and form of C++ are in order. First, for the most part, C++ programs physically look like C programs. Like a C program, a C++ program begins execution at main( ). To include commandline arguments, C++ uses the same argc, argv convention that C uses. Although C++ defines its own, object-oriented library, it also supports all the functions in the C standard library. C++ uses the same control structures as C. C++ includes all of the built-in data types defined by C. Trc khi bn bt u, mt vi ch gii tng qut v bn cht v biu mu s a ra trong trnh t. u tin, dnh cho hu ht cc phn, theo ci nhn l tnh th cc chng trnh C++ trng nh cc chng trnh C. Cng nh C, mt chng trnh C++ cng bt u thi hnh bi hm main(). bao gm nhng i s bng c ch dng lnh (command-line), C++ cng s dng quy c argc, argv m C dng. Mc d C++c nh ngha vi nhng s hu bn thn, th vin hng i tng (object-oriented), n cng h tr nhng hm trong th vin chun ca C. C++ s dng cu trc iu khin nh C. C++ cng bao gm nhng kiu d liu c xy dng trong C. 9

This book assumes that you already know the C programming language. In other words, you must be able to program in C before you can learn to program in C++ by using this book. If you dont knowC, a good starting place is my book Teach Yourseft C, Third Edition (Berkeley: Osborne/McGraw-Hill, 1997). It applies the same systematic approach used in this book and thoroughly covers the entires C language. Quyn sch ny xem nh bn bit v ngn ng lp trnh C. Ni cch khc bn phi bit lp trnh trong C trc khi bn hc nhng chng trnh C++ c vit trong cun sch ny. Nu bn cha bit v C, hy bt u vi cun sch Teach yourseft C, Third Edition (Berkeley: Osborne/McGrawHill, 1997).Vic ng dng cch tip cn c h thng c s dng trong cun sch ny s bao ph ton vn ngn ng C. Note: This book assumes that you know how to compile and execute a program using your C++ compiler. If you dont, you will need to refer to your compilers instructions. (Because of the differences between compilers, it is impossible to give compolation instructions for each in this book). Since programming is best learned by doing, you are strongly urged to enter, compile, and run the examples in the book in the order in which they are presented. Ch : Cun sch ny cho rng bn bit bin dch v thc thi mt chng trnh bng trnh bin dch C++. Nu cha, bn s cn nhiu s hng dn hn bi trnh bin dch ca bn. (Bi v nhng s khc nhau gia cc trnh bin dch, s l khng kh thi khi a ra nhng s hng dn v s bin dch trong cun sch ny.) V chng trnh l bi hc thc hnh tt nht, nn bn cn phi mnh m tin n, bin dch v chy th nhng v d trong cun sch ny bit dc ci g ang hin din ng sau nhng v d y. 1.1. WHAT IS OBJECT-ORIENTED PROGRAMMING ?- LP TRNH HNG I TNG L G ? Object-oriented programming is a powerful way to approach the task of 10

programming. Since its early beginnings, programming has been governed by various methodologies. At each critical point in the evolution of programming, a new approach was created to help the programmer handle increasingly complex programs. The first programs were created by toggling switches on the front panel of the computer. Obviously, this approach is suitable for only the smallest programs. Next, assembly language was invented, which allowed longer programs to be written. The next advance happened in the 1950s when the first high-level language (FORTRAN) was invented. Lp trnh hng i tng l con ng mnh m tip cn nhim v lp trnh. T bui bnh minh, lp trnh b chi phi bi nhiu phng php khc nhau. Ti mi thi im cch tn trong s pht trin ca lp trnh, mt cch tip cn mi li ra i vi mc ch gip lp trnh vin gia tng kh nng kim sot hay iu khin nhng chng trnh mang tnh phc tp. Nhng chng trnh u tin c to ra bi nhng cng tc o chiu c gn trn mt ci bng pha trc my tnh. Hin nhin l cch tip cn ny ch p ng c cho nhng chng trnh nh nht. Tip theo, ngn ng assembly (hay cn gi l Hp ng) c ra i, cho php vit nhng chng trnh di hn. Mt ngn ng cp cao hn xut hin vo nhng nm ca thp nin 1950 khi ngn ng cp cao u tin c ra i ( l FORTRAN). By using a high-level language, a programmer was able to write programs that were several thousands lines long. However,the method of programming used early on was an ad hoc, anything-goes approach. While this is fine relatively short programs, it yields unreadable (and unmanageable) spaghetti code when applied to larger programs. The elimination of spaghetti code became feasible with the invention of structured programming languages in the 1960s. These languages include Algol and Pascal. In loose terms, C is a structured language and most likely the type of programming relies on well-defined control structures, code blocks, the absence (or at least minimal use) of GOTO, and stand-alone subroutines that support recursion and local variables. The essence of structured programming is the reduction of a program into its constituent elements. Using structured programming, the average programmer can create and maintain programs that are up to 50,000 lines long. Bng vic s dng ngn ng cp cao, cc lp trnh vin c th vit nn nhng chng trnh c di ln ti vi ngn dng. Tuy nhin, phng php lp trnh ny cng ch c s dng nh mt th tm thi, khng g tin trin c. Trong khi nhng mi quan h gia cc chng trnh ngn kh kh quan 11

th vic thit k li qu kh (v khng kim sot c) loi m spaghetti ny khi ng dng cho cc chng trnh c ln. Cuc u tranh vi loi m spaghetti ny to cho s pht minh ra cu trc ca nhng ngn ng lp trnh vo thp nin 1960. Nhng ngn ng ny l Algol v Pascal. Trong tng lai khng chc chn, C l mt ngn ng c cu trc v gn nh l kiu lp trnh m bn bn ang dung vi tn gi l lp trnh c cu trc. Lp trnh cu trc da trn nhng cu trc iu khin, nhng khi m d xc nh, s vng mt (hay gn nh rt t s dng) ca GOTO, v nhng th tc con ng mt mnh h tr cho phng php quy v nhng bin cc b. Bn cht ca lp trnh cu trc l s gim thiu nhng yu t cu thnh bn cht bn trong ca mt chng trnh. Bng vic s dng phng php lp trnh ny, nhng lp trnh vin vi nng lc trung bnh cng c th to ra v bo tr nhng chng trnh m c khi lng ln ti 50.000 dng. Although structured programming has yielded excellent results when applied to moderately complex programs, even it fails at some point, after a program reaches a certain size. To allow more complex programs to be written, a new approach to the job of programming was needed. Towards this end, objectoriented programming was invented. OOP takes the best of ideas embodied in structured programming and combines them with powerful new concepts that allow you to organize your programs more effectively. Object-oriented programming encourages you to decompose a problem into its constituent parts. Each component becomes a seft-contained object that contains its own instructions and data that relate to that object. In this way, complexity is reduced and the programmer can manage larger programs. Mc d lp trnh cu trc t c nhng kt qu xut sc khi ng dng vo nhng chng trnh c phc tp trung bnh, thm ch ch trc trc vi ch sau khi mt chng trnh t n mt kch thc chc chn. cho php vit c nhng chng trnh phc tp hn, mt cch tip cn mi cng vic lp trnh c ra. Cui cng, phng php lp trnh hng i tng c pht minh. Lp trnh hng i tng (OOP) c th ha nhng tng tuyt vi vo trong cu trc lp trnh v kt hp chng vi nhng khi nim cht ch m cho php bn t chc nhng chng trnh ca mnh mt cch c hiu qu. OOP khuyn khch bn phn tch mt vn nm trong bn cht ca n. Mi b phn u c th tr thnh mt i tng c lp m cha ng nhng cu lnh hay d liu lien quan n i tng . Bng cch ny s phc tp s c gim xung v lp trnh vin c th qun l nhng chng trnh c ln. 12

All OOP languages, including C++, share three common defining traits: encapsulation, polymorphism, and inheritance. Lets look at the three concepts now. Tt c nhng ngn ng lp trnh hng i tng, bao gm c C++, u mang ba c im chung sau y: tnh ng gi, tnh a dng, v tnh k tha. Cn ch g na phi tm hiu cc khi nim trn ngay thi. Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates, and keep both safe from outside interference and misuse. In an object-oriented language, code and data can be combined in such a way that a seftcontained black box is created. 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. Tnh ng gi hay tch hp: Tnh ng gi l vic rng buc nhng on m v nhng d liu li, iu khin v gi chng an ton khi nhng nh hng v nhng mc ch sai tri. Trong mt ngn ng lp trnh hng i tng, m v d liu c th c kt hp theo cch m mt ci hp en c lp c to ra. Khi m v d liu lin kt vi nhau theo kiu ny th mt i tng c to nn. Ni cch khc, mt i tng l sn phm ca s ng gi vi nguyn liu l m v d liu. With an object, 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 cant be accessed by a piece of the program that exists outside the object. When code and data is public, other parts of your program can access it even though it is defined within an object. Typically, the public parts of an object are used to provide a controlled interface to the private elements of the object. Trong phm vi ca mt i tng, m, d liu , hay c hai c th l phn private (phn ring) ca i tng hay l public (phn chung). Phn m v d liu trong phn private c bit v truy xut bi cc thnh phn khc ca i 13

tng. Ngha l m v d liu trong phn private khng th c truy xut bi bt k phn no trong chng trnh m tn ti bn ngoi i tng . Khi m v d liu l kiu public th mi phn trong chng trnh ca bn u c th truy xut n n ngay c khi n c nh ngha bn trong mt i tng. c trng l nhng phn c kiu public ca mt i tng th c s dng cung cp mt giao din iu khin nhng thnh phn kiu private ca mt i tng. For all intents and purposes, an object is variable of a user-defined type. It may seem strange that an object that links both code and data can be thought of as a variable. However, in an object-oriented programming, this is precisely the case. Each time you define a new type of object, you are creating new data type. Each specific instance of this data type is a compound variable. ph hp vi nhiu nh v mc ch, mt i tng c th xem l mt bin theo kiu ngi dng t nh ngha. C th bn s ly lm ngc nhin khi mt i tng c th lin kt nhng lnh(hay m) v d liu li m li xem nh l mt bin. Tuy vy, trong lp trnh hng i tng th iu l hon ton chnh xc. Mi khi bn nh ngha mt loi i tng th bn ang to ra mt kiu d liu mi. Mi mt kiu i tng nh vy c coi l mt bin phc hp (hay bin ghp). Polymorphism Polymorphism (from the Greek,meaning many form) is the quality that allows one name to be used for two or more related but technically different purposes. As it relates to OOP, polymorphism allows one name to specify a general class of actions. Within a general class of actions, the specific action are be replied is determined by the type of data. For example, in C, which does not significantly support polymorphism, the absolute value action requires three distinct function names: abs( ), labs( ), and fabs( ). Three functions compute and return the absolute value of an integer, a long integer, and float-point value, respectively. However, in C++, which supports polymorphism, each function can be called by the same name, such as abs( ). (One way this can be accomplished is shown later in the chapter.) The type of the data used to call the function determines which 14

specific version of the function is actually executed. As you will see, in C++, it is possible to use ine function name for many different purposes. This is called function overloading. Tnh a dng Polymorphism (Theo ting Hy Lp c ngha l a th ) hay tnh a dng l c tnh cho php mt tn c th c s dng cho hai hay nhiu h nhng vi nhiu mc ch ng ngha khc nhau. V n lin quan n OOP, nn tnh a dng cho php mt tn ch r nhng hnh ng chung ca mt lp. Bn trong nhng hnh ng chung ca mt lp, hnh ng c trng ng dng c nh ngha bi mt kiu d liu. V d, trong C, th tnh a dng khng c h tr mt cch ng k, hnh ng ly gi tr tuyt i i hi ba tn hm ring bit l: abs( ), labs( ), fabs( ). Nhng hm ny tnh ton v tr li gi tr tuyt i ca mt s nguyn, mt s nguyn di, v mt s thc mt cch ring bit. Tuy nhin, trong C++, c h tr cho tnh a dng th ch cn mi hm abs( ). (Cch ny s c nu y trong phn sau ca chng ny). Kiu d liu dng trong hm s quyt nh vic hm no s c gi thc thi. Bn s thy, trong C++, hon ton c th s dng mt tn hm cho nhiu mc ch khc nhau. iu ny cn c gi l s qu ti hm (function overloading). More generally, the concept of polymorphism is characterized by the idea of one interface, multiple methods, which means using a generic interface for a group of related activities. The advantage of polymorphism is that it helps to reduce complexity by allowing one interface to specify a general class of action. It is the compilers job to select the specific action as it applies to each situation. You, the programmer, dont need to do this selection manually. You need only remember and utilize the general interface. As the example in the preceeding paragraph illustrates, having three names for the absolute value function instead of just one makes the general activity of obtaining the absolute value of a number more complex than it actually is. Tng qut hn, khi nim tnh a dng c c trng bi tng mt giao din nhng nhiu cch thc , iu ny c ngha l s dng mt giao din chung cho mt nhm nhng hnh ng c lin quan. S thun li ca tnh a dng l gip gim bt s phc tp bng cch cho php mt giao din ch r hnh ng ca mt lp tng qut. l cch m trnh bin dch chn hnh ng c trng thi hnh trong tng tnh hung c th. Bn, mt ngi lp trnh, khng cn phi lm cng vic ny mt cch th cng. Bn cn nh v 15

tn dng ci giao din chung. Nh th d minh ha trong on vn trc, cn n ba tn hm ly gi tr tuyt i thay v ch cn mt tn nhng ch hnh ng chung l tnh gi tr tuyt i ca mt s m tht s phc tp. Polymorphism can be applied to operators, too. Virtually all programming languages contain a limited application of polymorphism as it relates to the arithmetic operators. For example, in C++, the + sign is used to add integers, long intefer, characters, and floating-point values. In these cases, the compiler automatically knows which type of arithmetic to apply. In C++, you can extend this concept to other types of data that you define. This type of polymorphism is called operator overloading. Tnh a dng cng c th s dng cho cc ton t. Hu nh mi ngn ng lp trnh u c mt s gii hn tnh a dng i vi cc ton t s hc. V d, trong C, du + c dung cng cc gi tr s nguyn, s nguyn di, k t v s thc. Trong nhng trng hp ny, trnh bin dch t ng hiu loi s hc no s c p dng. Trong C++, bn c th m rng khi nim ny i vi nhng kiu d liu khc m bn nh ngha. Loi a dng ny c gi l s qu ti cc ton t (operator overloading). The key point to remember about polymorphism is that it allows you to handle greater complexity by allowing the creation of stamdard interfaces to related activities. im mu cht ca vn cn nh l tnh a dng cho php bn kim sot vi phc tp rt cao bng cch cho php to ra mt giao din tiu chun cho cc hnh ng c lin quan. Inheritance Inheritance is the process by which one object can be acquire the properties of another. More specifically, an object can inherit a general set of properties to which it can add those features that are specific only to itself. Inheritance is important because it allows an object to support the concept of hierarchical classification. Most information is made manageable by hierarchical classification. For example, think about the description of a house. A house is part of the general called building. In turn, building is 16

part of the more general class structure, which is part of the even more general of objects that we call man-made. In each case, the child class inherits all those qualities associated with the parent and adds to them its own defining characteristics. However, through inheritance, it is possible to describe an object by stating what general class (or classes) it belongs to along with those specific traits that make it unique. As you will see, inheritace plays a very important role in OOP. Tnh k tha Tnh k tha l mt qu trnh m mt i tng c th s dng cc c tnh ca mt i tng khc. C th hn, mt i tng c th tha hng nhng c tnh chung ca i tng khc thm cc tnh nng khc ny vo nh mt phn ca chnh bn thn n. S tha hng rt quan trng bi v n cho php mt i tng chp nhn khi nim s phn loi c tn ti (hierachial classification). Hu ht cc thng tin c to ra c qun l bi s s phn loi c trt t ny. V d, hy ngh v mt ngi nh. Mt ngi nh l mt phn ca mt lp tng qut gi l cng trnh. C nh vy, cng trnh li l mt phn ca mt lp chung gi l kin trc, v kin trc li l thnh phn ca mt lp m ta gi l nhng vt phm nhn to. Trong mi trng hp, lp con tha hng tt c nhng tnh cht c lin i vi lp cha v cng thm vi nhng tnh cht c nh ngha bn trong chng. Nu khng s dng s phn loi c trt t th mi i tng s phi nh ngha tt c nhng c tnh m r rng lin quan n n. Tuy nhin, qua s k tha, ta c th m t mt i tng bng cch pht biu nhng c im ni bt thuc v mt lp tng qut (hay mt h cc lp) m to nn tnh c nht ca chng. Bn s thy rng s tha hng chim mt vai tr rt quan trng trong OOP. CC V D : 1.S ng gi khng phi l iu g hon ton mi m trong OOP. Theo mt gc th s ng gi c th l mt thnh tu khi s dng ngn ng C. V d, khi bn s dng mt hm ca th vin th tht ra bn ang s dng th tc ci hp en, nhng g bn trong bn u th gy nh hng hay tc ng vo chng (tr phi, c l l ch b tay vi nhng hnh ng c tnh ph hoi). Hy xem xt hm fopen( ), khi dng m mt file, th vi bin ni b s c khi to v gn gi tr. Cng xa khi vng chng trnh lin quan th cng b n v kh truy cp. Tuy nhin, C++ vn cung cp cho bn nhiu cch tip cn s ng gi ny an ton hn. 2.Trong th gii thc, nhng v d v s a dng th kh l chung chung. V d, hy xem xt ci v-lng li xe ca bn. N lm vic cng ging nh chic xe bn s dng thit b li nng lng, thit b li bng thanh rng, hay tiu chun, thit 17

b li th cng. Vn l ci b ngoi hnh dng khng quan trng m l ci cch cc ng c bnh rng hot ng (hay ci phng thc). 3.S tha k cc c tnh v khi nim tng qut hn v lp l nn tng hiu cch t chc. V d, rau cn ty l mt loi(hay thnh vin) ca lp rau qu, rau qu li l mt thnh phn ca lp cy trng. Ln lt nh vy, cy trng l nhng sinh vt sng, v c th. Nu khng c s s phn loi trong tn ti th h thng h thng kin thc s khng kh thi. BI TP: Hy ngh v vai tr ca s phn loi v tnh a dng trong cuc sng hng ngy ca chng ta. 1.2. TWO VERSIONS OF C++ - HAI PHIN BN CA C++ At the time of this writing, C++ is in the midst of a transformation. As explained in the preface to this book, C++ has been undergoing the process of standardization for the past several years. The goal has been to create a stable, standardized, featured-rich language, that will suit the needs of programmers well into the next century. As a result, there are really two versions of C++. The first is the traditional version that is based upon Bjarne Stroustrups original designs. This is the version of C++ that has been used by programmers for the past decade. The second is the new Standard C++, which was created by Stroustrup and the ANSI/ISO standardization committee. While these two versions of C++ are very similar at there core, Standard C++ contains several enhancements not found in traditional C++. Thus, Standard C++ is essentially a superset of traditional C++. Vo thi im vit cun sch ny, C++ l ci chuyn giao ca mt s thay i. Nh ni trong phn m u ca cun sch, C++ phi tri qua mt qu trnh chun ha trong vi nm trc y. Mc tiu l to ra s n nh, c chun ha, mt ngn ng giu tnh nng phc v tt cho cc lp trnh vin trong th k tip theo. Kt qu l to ra hai phin bn C++. Ci u tin l phin bn truyn thng m da trn ngun gc bn phc tho ca Bjarne Stroustrup. y l phin bn C++ c cc lp trnh vin s dng trong thp nin trc y. Ci th hai l new Standard C++, c to ra bi Stroustrup v y ban tiu chun ANSI/ISO. Trong khi hai phin bn C++ c ht nhn kh l ging nhau th Standard C++(hay C++ chun) cha vi s ni bt m khng 18

tm thy c trong phin bn C++ truyn thng. V vy, C++ chun mt cch c bit l mt tp cha ca bn C++ truyn thng. This book teaches Standard C++. This is the version of C++ defined by the ANSI/ISO standardization committee, and it is the version implemented by all modern C++ compilers. The code in this book reflects the contemporary coding style and practices as encouraged by Standard C++. This means that what you learn in this book will be applicable today as well as tomorrow. Put directly, Standard C++ is the future. And, since Standard C++ encompasses all features found in earlier versions of C++, what you learn in this book will enable you work in all C++ programming environments. Cun sch ny vit v C++ chun. Phin bn ny c nh ngha bi y ban tiu chun ANSI/ISO, v n l cng c ca tt c cc trnh bin dch C++ hin nay. Nhng on m vit trong cun sch ny tng ng vi phong cch vit m ng thi v nhng bi thc hnh theo bn C++ chun. iu ny c ngha l nhng g bn hc trong cun sch ny th u s dng c hin nay cng nh tng lai. Ni trc tip l C++ chun chnh l tng lai. V, v C++ hon thin tt c cc tnh nng c trong cc bn C++ trc nn tt c nhng g bn hc u c th lm vic trong tt c cc mi trng lp trnh C++. However, if you are using an older compiler, it might not accept all the programs in this book. Heres why: During the process of standardization, the ANSI/ISO committee added many new features to the language. As these features were defined, they were implemented by the compiler developers. Of course, there is always a lag time between the addition of a new feature to the language and the availability of the features in commercial compilers. Since features were added to C++ over a period of years, an older compiler might not support one or more of them. This important because two recent additions to the C++ language affect every program that you will write-even the simplest. If you are using an oder compiler that does not accept these new features, dont worry. There is an easy workaround, which is described in the following paragraphs. Tuy nhin, nu bn s dng mt trnh bin dch qu c, th c kh nng n s khng chp nhn nhng on m vit trong cun sch ny. y cng l nguyn nhn m trong sut qu trnh chun ha, y ban tiu chun ANSI/ISO tng thm nhiu tnh nng mi cho ngn ng ny. Khi nhng tnh nng ny c nh ngha th chng cng c cc nh pht trin trnh bin dch b 19

sung. Tt nhin y lun l mt khong thi gian chm chp gia vic thm tnh nng vo mt ngn ng v vic bin n kh thi trong cc trnh bin dch. Nhng tnh nng ny c thm vo trong mt thi k nhiu nm nn nhng trnh bin dch i c th khng c h tr bin dch chng. V quan trng hn l hai s b sung gn y vo ngn ng C++ s nh hng n mi chng trnh m bn s vit, thm ch d l chng trnh n gin nht. Nu bn s dng trnh bin dch c hn th n s khng chp nhn nhng tnh nng mi ny, nhng ng qu lo lng. C mt cch gii quyt d dng s c m t trong nhng on tip theo. The differences between old-style and modern code involve two new features: new-style headers and the namespace statement. To demonstrate these deffirences we will begin by looking at two versions of a minimal, donothing C++ program. The first version, shown here, reflects theway C++ programs were written until recently. (That is, it uses old-style coding.) S khc bit gia phong cch vit m c v hin i lin quan n hai tnh nng sau: nhng kiu khai bo mi v s gii thiu khng gian tn (namespace). chng minh nhng s khc bit ny chng ti s bt u bng vic nhn li hai bn C++ mt kha cnh nh, khng ng n chng trnh C++. Trong bn u tin, hy xem sau y, phn nh cch nhng chng trnh C++ c vit trong thi gian gn y. ( l vit m theo phong cch c.) /* Nhng chng trnh vi phong cch C++ truyn thng /* #include int main() { /* vng m chng trnh */ return 0; } 20

Since C++ is built on C, this skeleton should be largely familiar, but pay special attention to the #include statement. This statement includes the file iostream.h, which provides support for C++s I/O system. (It is to C++ what stdio.h is to C.) Here is the second version of the skeleton, which uses the modern style: V C++ c xy dng da trn C, nn ci khung rt quen thuc nhng hy ch n dng pht biu #include. Li pht biu ny khai bo file iostream.h m c cung cp cho h thng nhp xut ca C++ (trong C l stdio.h). Sau y l bn th hai ca ci khung ny, s dng phong cch hin i: /* Phong cch lp trnh C++ hin i l s dng li khai bo theo phong cch mi v vng khng gian tn */ #include using namespace std; int main() { /* vng m chng trnh */ return 0; } Notice the two lines in this program immediately after the first comment; this is where the changes occur. First, in the #include statement, there is no .h after the name iostream. And second, the next line, specifying a namespace, in new. Although both the new-style headers and namespaces will be examined in detail later in this book, a brief overview is in order now. 21

Ch hai dng trong chng trnh ny ngay lp tc sau khi c xong li nhn xt u tin; y c s thay i. y tin, trong li pht biu #include khng c .h theo sau tn iostream. V ci th hai l dng tip theo, ch r vng khng gian tn, y l nt mi. Mc d c hai ci ny s c kim nghim chi tit trong cc phn sau ca cun sch nhng chng ta hy xem xt ngn gn chng. The new C++ headers As you know from your C programming experience, when you use a library function in a program, you must include its header file.This is done using the #include statement. For example, in C, to include the header file for the I/O functions, you include stdio.h with a statement like this. Nhng u mc mi ca C++ Nh bn bit t nhng kinh nghim lp trnh bng C++, khi bn s dng mt hm th vin trong mt chng trnh, bn phi bao hm li khai bo file. Ci ny dng cch pht biu #include. V d, trong C, khai bo s dng file cho hm I/O (hm nhp xut), bn s dng stdio.h vi li pht biu nh sau: #include Here stdio.h is the name of the file used by the I/O functions, and the preceding statement causes that file to be included in your program. The key point is that the #include statement includes a file. y, stdio.h l tn file c s dng bi hm nhp xut, v vic li pht biu ny i trc lm cho file c bao hm trong chng trnh ca bn. im mu cht l #include pht biu vic includes a file (bao hm mt file). When C++ was first invented and for several years after that,it used the same style of headers ad did C. In fact, Standard C++ still supports C-style headers for header files that you create and for backward compatibility. However, Standard C++ has introduced a new kind of header that is used by the Standard C++ library. The new-style headers do not specify filenames. Instead, they simply specify standard identifiers that might be mapped to files by the compiler, but they need not be. The new-style C++ 22

headers are abstractions that simply guarantee that the appropriate prototypes and definitions required by the C++ library have been declared. Khi C++ ln u tin c to ra v vi nm sau , n s dng nhng kiu khai bo ca C. Tht ra, C++ chun vn cn h tr nhng khai bo kiu C cho nhng file khai bo m bn to ra v cho s tng thch ngc. Tuy nhin, C++ chun gii thiu mt kiu khai bo mi m c s dng trong th vin C++ chun. Kiu khai bo mi ny khng ch r tn nhng file. Thay v n gin ch r nhng nh dng tiu chun m chng c nh x vo cc file bi trnh bin dch nhng chng khng cn. Kiu khai bo mi ny ca C++ l nhng s tru tng ha nh s m bo n thun, nhng vt mu hay nhng nh ngha thch ng c yu cu bi th vin C++. Since the new-style header is not a filename, it does not have a .h extension. Such a header consist solely of the header name contained between angle brackets supported by Standard C++. V khai bo mi khng phi l mt tn file nn ui .h khng cn thit. Mt khai bo gm c mt tn khai bo n c trong du ngoc < >. V d, sau y l vi kiu khai bo c chp nhn trong C++ chun: The new-style headers are included using the #include statement. The only difference is that the new-style headers do not necessarily represent filenames. Nhng u mc kiu mi ny bao gm vic s dng s trnh by #include. S khc nhau duy nht l nhng u mc kiu mi khng tt yu i din cho tn file. Becase C++ includes th entire C function library, it still supports the standard C-style header files associated with that library. That is, header files such as stdio.h and ctype.h are still available. However, Standard C++ also defines newstyle headers you can use in place of these header files. The C++ versions of the standard C headers simply add c prefix to the filename and drop the .h. For example, the new-style C++ header for math.h is , and the one for 23

string.h is . Although it is currently permissible to include a C-tyle header file when using C library functions, this approach is deprecate by Standart C++.(That is, it is not recommended.) For this reason, this book will use newstyle C++ header in all #include statements. If your compiler does not support new-style headers for the C function library, simply substitute the oldstyle, Clike headers. Bi v C++ bao gm ton b th vin chc nng C, n vn cn h tr C tiu chunnhng h s u mc kiu lin quan n th vin kia. iu , u mc sp xp nh stdio.h v ctype.h th vn cn sn c. Tuy nhin, C++ tiu chun cng nh ngha nhng u mc kiu mi bn c th s dng thay cho nhng h s u mc ny. Nhng phin bn C++ ca nhng u mc C tiu chun n gin thm tin t c vo u tn file v kt thc bng .h .Chng hn, u mc C++ kiu mi cho math.h l , v cho string.h l < cstring>. D hin thi tha nhn bao gm mt h s u mc tyle C khi s dng nhng hm th vin C, phng php ny b phn i bi C++ chun.(Ngha l, n khng c khuyn co.). Vi l do ny, sch ny s s dng u mc C++ kiu mi trong tt c cc cu lnh. Nu trnh bin dch (ca) cc bn khng h tr nhng u mc kiu mi cho th vin chc nng C, n gin th nhng u mc c, ging nh C. Since the new-style header is a recent addition to C++, you will still find many, many older programs that dont use it. These programs instead use C-tyle headers, in which a filename is specified. As the oldstyle skeletal program shows, the traditional way to include the I/O header is as shown here: u mc kiu mi l mt s b sung cho C++, bn s vn cn tm thy gn y nhiu chng trnh c khng s dng n. Nhng chng trnh ny thay vo s dng C- nhng u mc tyle, trong mt tn file c ch r. Nh chng trnh lnh iu khin kiu c hin ra, cch truyn thng bao gm u mc vo/ra c cho thy nh y: #include < iostream.h > This cause the file iostream.h to be include in your program. In general, an oldstyle header will use the same name as its corresponding new-style header with a .h appended. y l cn nguyn tp tin iostream.h c bao gm trong chng trnh ca cc bn. Ni chung, mt u mc kiu c s s dng cng tn vi u mc kiu mi tng ng vi n vi .h c ni vo. As of this writing, all C++ compilers support the old-style headers. However, the 24

old style headers have been declared obsolete, and their use in new programs is not recommended. This is why they are not used in this book. K t s ghi ny, tt c cc trnh bin dch C++ h tr nhng u mc kiu c. Tuy nhin, nhng u mc kiu c c khai bo li thi, v s s dng chng trong nhng chng trnh mi khng c khuyn co. iu ny l l do ti sao chng khng c s dng trong sch ny. Remember: While still common in existing C++ code, old-style headers are obsolete. Ghi Nh : Trong m C++ ph bin hin hu, nhng u mc kiu c l li thi. NAMESPACES When you include a new-style header in your program, the contents of that header are contained in the std namespace. A namespace is simply a declarative region. The purpose of a namespace is to localize the names of library functions and other such items were simply placed into the global namespace(as they are in C). However, the contents of new-style headers are placed in the std namespace. We will look closely at namespace later in this book. For now, you dont need to worry about them because you can use the statement. Khi bn bao gm mt u mc kiu mi trong chng trnh ca cc bn, ni dung ca u mc kia c cha ng trong namespace std . Mt namespace n gin l mt vng tng thut. Mc ch ca mt namespace l s a phng ha tn ca nhng hm th vin v nhng th mc nh vy khc th n gin c t vo trong ton cc namespace (ging nh trong C). Tuy nhin, ni dung ca nhng u mc kiu mi c t trong namespace std. Chng ti s c ci nhn r rng hn v namespace trong cun sch ny phn sau. By gi, bn khng cn lo lng h bi v bn c th s dng cu lnh using namespace std; to bring the std namespace into visibility (i.e., to put std into the global namespace). After this statement has been complied, there is no difference between working with an old-style header and a new-style one. mang n s r rng cho namespace std ( th d, std c t vo trong namespace ton cc). Sau khi cu lnh ny c tun theo, khng c s khc nhau 25

gia vic lm vic vi mt u mc kiu c v mt u mc kiu mi. Lm vic Vi mt Trnh bin dch c (WORKING WITH AN OLD COMPILER): As mentioned, both namespaces and the new-style headers are recent additions to the C++ language. While virtually all new C++ compilers support these features, older compilers might not. If you have one of these older compilers, it will report one or more errors when it tries to compile the first two lines of the sample programs in this book. If this is the case, there is an easy workaround: simply use an old-style header and delete the namespace statement. That is, just replace Nh cp, c namespaces ln nhng u mc kiu mi l s b sung cho ngn ng C++ gn y. Trong khi thc t tt c cc trnh bin dch C++ mi h tr nhng c tnh ny, nhng trnh bin dch c hn c l khng h tr. Nu bn c mt trong s nhng trnh bin dch c ny, n s bo co mt hoc nhiu li khi n th bin tp nhng dng u tin trong chng trnh mu trong cun sch ny. Nu l nguyn nhn, c mt cch gii quyt d dng: n gin s dng mt u mc kiu c v xa khai bo namespace. iu , thay th #include using namespace std; bng #include This change transforms a modern program into a traditional-style one. Since the old-style header reads all of its contents into the global namespace, there is no need for a namespace statement. 26

S thay i ny thay i mt chng trnh hin i vo trong mt kiu truyn thng. Mt khi u mc kiu c bin dch tt c cc ni dung lm bng lng namespace ton cc, th khng c nhu cu phi khai bo namespace. One other point: For now and for the next few years, you will see many C++ programs that use the old-style headers and that do not include a namespace statement. Your C++ compiler will be able to compile them just fine. For new programs, however, you should use the modern style because it is the only style of program that compiles with Standard C++. While old-style programs will continue to be supported for many years, they are technically noncompliant. Mt im khc: by gi v trong nhng nm tip theo, bn s nhn thy nhiu chng trnh C++ m s dng nhng u mc kiu c m khng bao gm cu lnh namespace. Trnh bin dch C ++ ca cc bn s c kh nng bin tp chng mt cch chnh xc. Cho nhng chng trnh mi, tuy nhin, bn nn s dng kiu mi bi v l kiu duy nht ca chng trnh m s bin tp ph hp vi C++ tiu chun. Trong khi nhng chng trnh kiu c s tip tc c h tr trong nhiu nm, th chng l k thut khng tng hp. EXERCISE 1. Before proceeding, try compiling the new-style skeleton program shown above. Although it does nothing , compiling it will tell you if your compiler supports the modern C++ syntax. If it does not accept the new-style headers or the namespace statement, substitute the old-style header as described. Remember, if your compiler does not accept new-style code, you must make this change for each program in this book. Bi tp 1. Trc khi tip tc, th bin tp chng trnh iu khin kiu mi c cho thy trn. Mc d n khng l g, hy bin tp n s cho bn bit nu trnh bin dch ca bn h tr c php C++ hin i. Nu n khng chp nhn nhng u mc kiu mi hay khai bo namespace, thay th u mc kiu xa nh c m t. Nh, nu trnh bin dch ca bn khng chp nhn m kiu mi, bn phi lm s thay i ny cho mi chng trnh trong sch ny. 27

1.3. C++ CONSOLE C++ I / O - BN GIAO TIP NHP/XUT Since C++ is a superset of C, all elements of the C language are also contained in the C++ language. This implies that all C programs are also C++ programs by default.(Actually, there are some very minor exceptions to this rule, which are discussed later in this book.) V C++ l siu tp hp ca C nn mi phn t ca ngn ng C u c cha trong ngn ng C++. iu ny ch ra rng cc chng trnh C cng l cc chng trnh C++. (Thc s, c mt vi ngoi l nh i vi quy tc s c tho lun vo cui sch). Therefore, it is possible to write C++ programs that look just like C programs. While there is nothing wrong with this per se, it dose mean that you will not be taking full advange of C++. To get the maximum benefit from C++, you must write C++-style programs. This means using a coding style and features that are unique to C++. Do c th vit cc chng trnh C++ trng ging nh cc chng trnh C.Hu ht nhng ngi lp trnh C++ vit cc chng trnh s dng kiu v cc c im duy nht cho C++. L do l gip bn bt u lm quen vi cc thut ng C++ thay v ngh v C. Cng vy, bng cch dng cc c im C++, bn s cho ngi khc hiu ngay chng trnh ca bn l C++ ch khng phi l chng trnh C. Perhaps the most common C++-specific feature used by C++ programmers is its approach to console I/O. While you may still use functions such as printf() anh scanf(), C++ provides a new, and better, way to perform these types of I/O operations. In C++, I/O is performed using I/O operators instead of I/O function. The output operator is >. As you know, in C, these are the left and right shift operators, respectively. In C++, they still retain their original meanings (left and right shift) but they also take on the expanded role of performing input and output. Consider this C++ statement: C l c im thng dng nht ca C++ c nhng ngi lp trnh C++ s dng l bn giao tip nhp/xut. Trong khi bn vn s dng nhng hm nh printf() v scanf(), C++ a ra mt cch mi v tt hn thc hin cc thao tc nhp/xut ny. Trong C++, nhp/xut c thc hin bng cch dng cc ton t nhp/xut thay v cc hm nhp/xut.Ton t xut l >. Nh bn bit, trong C y l nhng ton t dch chuyn phi v tri. Trong C++, chng vn 28

cn ngha gc (dch chuyn phi v tri) nhng chng cng c mt vai tr m rng thc hin nhp xut. Xt cu lnh C++ sau: cout . Tng qut, nhp mt gi tr t bn phm th dng dng >>: cin >> variable; Note: The expanded roles of > are examples of operator overloading. Ch : Cc vai tr m rng ca > l nhng v d v qu ti ton t. In order to use the C++ I/O operators, you must include the header in your program. As explained earlier, this is one of C++s standard headers and is supplied by your C++ compiler. s dng cc ton t Nhp/Xut C++, bn phi ghi r file tiu iostream.h trong chng trnh ca bn. y l mt trong nhng file tiu chun ca C++ do trnh bin dch C++ cung cp. CC V D (EXAMPLES): 1. This program outputs a string, two integer values, and a double floating-point value: 1. Chng trnh sau xut mt chui, hai gi tr nguyn v mt gi tr du phy ng kp: #include 30

using namespace std; int main() { int i, j; double d; i = 10; j = 20; d = 99.101; cout