You are on page 1of 103

Bi 1.

1: Cu trc ca mt chng trnh C++


C l mt trong nhng cch tt nht bt u hc mt ngn ng lp trnh l bng mt chng trnh. Vy y l chng trnh u tin ca chng ta :
// my first program in C++ #include <iostream.h> int main () { cout << "Hello World!"; return 0; } Hello World!

Chng trnh trn y l chng trnh u tin m hu ht nhng ngi hc ngh lp trnh vit u tin v kt qu ca n l vit cu "Hello, World" ln mn hnh. y l mt trong nhng chng trnh n gin nht c th vit bng C++ nhng n bao gm nhng phn c bn m mi chng trnh C++ c. Hy cng xem xt tng dng mt :
// my first program in C++

y l dng ch thch. Tt c cc dng bt u bng hai du s (//) c coi l cht thch m chng khng c bt k mt nh hng no n hot ng ca chng trnh. Chng c th c cc lp trnh vin dng gii thch hay bnh phm bn trong m ngun ca chng trnh. Trong trng hp ny, dng ch thch l mt gii thch ngn gn nhng g m chng trnh chng ta lm.
#include <iostream.h>

Cc cu bt u bng du (#) c dng cho preprocessor (ai dch h ti t ny vi). Chng khng phi l nhng dng m thc hin nhng c dng bo hiu cho trnh dch. y cu lnh #include <iostream.h> bo cho trnh dch bit cn phi "include" th vin iostream. y l mt th vin vo ra c bn trong C++ v n phi c "include" v n s c dng trong chng trnh. y l cch c in s dng th vin iostream
int main ()

Dng ny tng ng vi phn bt u khai bo hm main. Hm main l im m tt c cc chng trnh C++ bt u thc hin. N khng ph thuc vo v tr ca hm ny ( u, cui hay gia ca m ngun) m ni dung ca n lun c thc hin u tin khi chng trnh bt u. Thm vo , do nguyn nhn ni trn, mi chng trnh C++ u phi tn ti mt hm main. Theo sau main l mt cp ngoc n bi v n l mt hm. Trong C++, tt c cc hm m sau l mt cp ngoc n () th c ngha l n c th c hoc khng c tham s (khng bt buc). Ni dung ca hm main tip ngay sau phn khai bo chnh thc c bao trong cc ngoc nhn ( { } ) nh trong v d ca chng ta
cout << "Hello World";

Dng lnh ny lm vic quan trng nht ca chng trnh. cout l mt dng (stream) output chun trong C+ + c nh ngha trong th vin iostream v nhng g m dng lnh ny lm l gi chui k t "Hello World" ra mn hnh. Ch rng dng ny kt thc bng du chm phy ( ; ). K t ny c dng kt thc mt lnh v bt buc phi c sau mi lnh trong chng trnh C++ ca bn (mt trong nhng li ph bin nht ca nhng lp trnh vin C++ l qun mt du chm phy).
return 0;

Lnh return kt thc hm main v tr v m i sau n, trong trng hp ny l 0. y l mt kt thc bnh thng ca mt chng trnh khng c mt li no trong qu trnh thc hin. Nh bn s thy trong cc v d tip theo, y l mt cch ph bin nht kt thc mt chng trnh C++. Chng trnh c cu trc thnh nhng dng khc nhau n tr nn d c hn nhng hon ton khng phi bt buc phi lm vy. V d, thay v vit
int main () { cout << " Hello World "; return 0; }

ta c th vit
int main () { cout << " Hello World "; return 0; }

cng cho mt kt qu chnh xc nh nhau. Trong C++, cc dng lnh c phn cch bng du chm phy ( ;). Vic chia chng trnh thnh cc dng ch nhm cho n d c hn m thi.

Cc ch thch.
Cc ch thch c cc lp trnh vin s dng ghi ch hay m t trong cc phn ca chng trnh. Trong C++ c hai cch ch thch
// Ch thch theo dng /* Ch thch theo khi */

Ch thch theo dng bt u t cp du x (//) cho n cui dng. Ch thch theo khi bt u bng /* v kt thc bng */ v c th bao gm nhiu dng. Chng ta s thm cc ch thch cho chng trnh :
/* my second program in C++ with more comments */ #include <iostream.h> int main () { cout << "Hello World! "; says Hello World! Hello World! I'm a C++ program

//

cout << "I'm a C++ program"; // says I'm a C++ program return 0; }

Nu bn vit cc ch thch trong chng trnh m khng s dng cc du //, /* hay */, trnh dch s coi chng nh l cc lnh C++ v s hin th cc li.

Bi 1.2: Cc bin, kiu v hng s


Identifiers
Mt tn (indentifiers) hp l l mt chui gm cc ch ci, ch s hoc k t gch di. Chiu di ca mt tn l khng gii hn. K t trng, cc k t nh du u khng th c mt trong mt tn. Ch c ch ci, ch s v k t gch di l c cho php. Thm vo , mt tn bin lun phi bt u bng mt ch ci. Chng cng c th bt u bng k t gch di ( _ ) nhng k t ny thng c dnh cho cc lin kt bn ngoi (external link). Khng bao gi chng bt u bng mt ch s. Mt lut na m bn phi quan tm n khi to ra cc tn ca ring mnh l chng khng c trng vi bt k t kho no ca ngn ng hay ca trnh dch, v d cc tn sau y lun lun c coi l t kho theo chun ANSI-C++ v do vy chng khng th c dng t tn
asm, car, bool, break, marry, catch, to char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, to register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t

Thm vo , mt s biu din khc ca cc ton t (operator) cng khng c dng lm tn v chng l nhng t c dnh ring trong mt s trng hp.
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Trnh dch ca bn c th thm mt t dnh ring c trng khc. V d, rt nhiu trnh dch 16 bit (nh cc trnh dch cho DOS) cn c th cc t kho far, huge v near. Ch : Ngn ng C++ l "case sensitive" c ngha l phn bit ch hoa ch thng. Do vy bin RESULT khc vi result cng nh Result.

Cc kiu d liu
Khi lp trnh, chng ta lu tr cc bin trong b nh ca my tnh nhng my tnh phi bit chng ta mun lu tr g trong chng v cc kiu d liu khc nhau s cn lng b nh khc nhau. 3

B nh ca my tnh chng ta c t chc thnh cc byte. Mt byte l lng b nh nh nht m chng ta c th qun l. Mt byte c th dng lu tr mt loi d liu nh nh l kiu s nguyn t 0 n 255 hay mt k t. Nhng my tnh c th x l cc kiu d liu phc tp hn bng cch gp nhiu byte li vi nhau, nh s nguyn di hay s thp phn. Tip theo bn s c mt danh sch cc kiu d liu c bn trong C++ cng nh min gi tr m chng c th biu din Tn char short long S byte M t 1 2 4 Min gi tr c du: -128 to 127 K t hay kiu s nguyn 8-bit khng du: 0 to 255 c du: -32763 to 32762 kiu s nguyn 16-bit khng du: 0 to 65535 c du:-2147483648 to kiu s nguyn 32-bit 2147483647 khng du: 0 to 4294967295 S nguyn. di ca n ph thuc vo h thng, nh trong MS-DOS n l 16-bit, trnXem short, long Windows 9x/2000/NT l 32 bit... Dng du phy ng 3.4e + / - 38 (7 digits) Dng du phy ng vi chnh xc gp 1.7e + / - 308 (15 digits) i Dng du phy ng vi chnh xc hn 1.2e + / - 4932 (19 digits) na Gi tr logic. N mi c thm vo chun ANSI-C++. Bi vy khng phi tt c cctrue hoc false trnh dch u h tr n.

int float

* 4

double 8 long 10 double bool 1

Ngoi cc kiu d liu c bn ni trn cn tn ti cc con tr v cc tham s khng kiu (void) m chng ta s xem xt sau.

Khai bo mt bin
c th s dng mt bin trong C++, u tin chng ta phi khai bo n, ghi r n l kiu d liu no. Chng ta ch cn vit tn kiu (nh int, short, float...) tip theo sau l mt tn bin hp l. V d
int float mynumber; a;

Dng u tin khai bo mt bin kiu int vi tn l a. Dng th hai khai bo mt bin kiu float vi tn mynumber. Sau khi c khai bo, cc bin trn c th c dng trong phm vi ca chng trong chng trnh. Nu bn mun khai bo mt vi bin c cng mt kiu v bn mun tit kim cng sc vit bn c th khai bo chng trn mt dng, ngn cch cc tn bng du phy. V d
int a, b, c;

khai bo ba bin kiu int (a,b v c) v hon ton tng ng vi :


int int int c; a; b;

Cc kiu s nguyn (char, short, long and int) c th l s c du hay khng du tu theo min gi tr m chng ta cn biu din. V vy khi xc nh mt kiu s nguyn chng ta t t kho signed hoc unsigned trc tn kiu d liu. V d:
unsigned signed int MyAccountBalance; short NumberOfSons;

Nu ta khng ch r signed or unsigned n s c coi l c du, v vy trong khai bo th hai chng ta c th vit :
int MyAccountBalance

cng hon ton tng ng vi dng khai bo trn. Trong thc t, rt t khi ngi ta dng n t kho signed. Ngoi l duy nht ca lut ny kiu char. Trong chun ANSI-C++ n l kiu d liu khc vi signed char v unsigned char. c th thy r hn vic khai bo trong chng trnh, chng ta s xem xt mt on m C++ v d nh sau:
// operating with variables #include <iostream.h> int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; 4

ng lo lng nu nh vic khai bo c v hi l lng vi bn. Bn s thy phn chi tit cn li trong phn tip theo

Khi to cc bin
5

Khi khai bo mt bin, gi tr ca n mc nhin l khng xc nh. Nhng c th bn s mun n mang mt gi tr xc nh khi c khai bo. lm iu , bn ch cn vit du bng v gi tr bn mun bin s mang:
type identifier = initial_value ;

V d, nu chng ta mun khai bo mt bin int l a cha gi tr 0 ngay t khi khi to, chng ta s vit :
int a = 0;
B xung vo cch khi to kiu C ny, C++ cn c thm mt cch mi khi to bin bng cch bc mt cp ngoc n sau gi tr khi to. V d :

int a (0);

C hai cch u hp l trong C++.

Phm vi hot ng ca cc bin


Tt c cc bin m chng ta s s dng u phi c khai bo trc. Mt im khc bit gia Cv C++ l trong C++ chng ta c th khai bo bin bt k ni no trong chng trnh, thm ch l ngay gia cc lnh thc hin ch khng ch l u khi lnh nh trong C. Mc d vy chng ta vn nn theo cch ca ngn ng C khi khai bo cc bin bi v n s rt hu dng khi cn sa cha mt chng trnh c tt c cc phn khai bo c gp li vi nhau. Bi vy, cch thng dng nht khai bo bin l t n trong phn bt u ca mi hm (bin cc b) hay trc tip trong thn chng trnh, ngoi tt c cc hm (bin ton cc). Global variables (bin ton cc) c th c s dng bt k u trong chng trnh, ngay sau khi n c khai bo. Tm hot ng ca local variables (bin cc b) b gii hn trong phn m m n c khai bo. Nu chng c khai bo u mt hm (nh hm main), tm hot ng s l ton b hm main. iu c ngha l trong v d trn, cc bin c khai bo trong hm main() ch c th c dng trong hm , khng c dng bt k u khc. Thm vo cc bin ton cc v cc b, cn c cc bin ngoi (external). Cc bin ny khng nhng c dng trong mt file m ngun m cn trong tt c cc file c lin kt trong chng trnh. Trong C++ tm hot ng ca mt bin chnh l khi lnh m n c khai bo (mt khi lnh l mt tp hp cc lnh c gp li trong mt bng cc ngoc nhn { } ). Nu n c khai bo trong mt hm tm hot ng s l hm , cn nu c khai bo trong vng lp th tm hot ng s ch l vng lp ....

Cc hng s
Mt hng s l bt k mt biu thc no mang mt gi tr c nh, nh: Cc s nguyn 6

1776 707 -273

chng l cc hng mang gi tr s. Ch rng khi biu din mt hng kiu s chng ta khng cn vit du ngoc kp hay bt k du hiu no khc. Thm vo nhng s h c s 10 ( ci m tt c chng ta u bit) C++ cn cho php s dng cc hng s c s 8 v 16. biu din mt s h c s 8 chng ta t trc n k t 0, biu din s h c s 16 chng ta t trc n hai k t 0x. V d:
75 0113 0x4b // C s 10 // c s 8 // c s 16

Cc s thp phn (dng du phy ng)

Chng biu din cc s vi phn thp phn v/hoc s m. Chng c th bao gm phn thp phn, k t e (biu din 10 m...).
3.14159 // 3.14159 6.02e23 // 6.02 x 1023 1.6e-19 // 1.6 x 10-19 3.0 // 3.0

K t v xu k t
Trong C++ cn tn ti cc hng khng phi kiu s nh:

'z' 'p' "Hello "How do you do?"

world"

Hai biu thc u tin biu din cc k t n, cc k t c t trong du nhy n ('), hai biu thc tip theo biu thc cc xu k t c t trong du nhy kp ("). Khi vit cc k t n hay cc xu k t cn phi chng trong cc du nhy phn bit vi cc tn bin hay cc t kho. Ch :
x 'x'

x tr n bin x trong khi 'x' l k t hng 'x'. Cc k t n v cc xu k t c mt tnh cht ring bit l cc m iu khin. Chng l nhng k t c bit m khng th c vit bt k u khc trong chng trnh nh l m xung dng (\n) hay tab (\t). Tt c u bt u bng du x ngc (\). Sau y l danh sch cc m iu khin :
\n

xung dng 7

\r \t \v \b \f \a \' \" \ \\

li v u dng k t tab cn thng theo chiu dc backspace sang trang Ku bp du nhy n du nhy kp du hi k t x ngc

V d:
'\n' '\t' "Left "one\ntwo\nthree"

\t

Right"

Thm vo , biu din mt m ASCII bn cn s dng k t x ngc (\) tip theo l m ASCII vit trong h c s 8 hay c s 16. Trong trng hp u m ASCII c vit ngay sau du s ngc, trong trng hp th hai, s dng s trong h c s 16 bn cn vit k t x trc s (v d \x20 hay \x4A). Cc hng chui k t c th c vit trn nhiu dng nu mi dng c kt thc bng mt du s ngc (\):
"string two lines" expressed in \

Bn c th ni mt vi hng xu k t ngn cch bng mt hay vi du trng, k t tab, xung dng hay bt k k t trng no khc. "we form" "a unique" "string" "of characters"

nh ngha cc hng (#define)


Bn c th nh ngha cc hng vi tn m bn mun c th s dng thng xuyn m khng mt ti nguyn cho cc bin bng cch s dng ch th #define. y l dng ca n:
#define identifier value

V d:
#define #define #define WIDTH 100 PI NEWLINE 3.14159265 '\n'

chng nh ngha ba hng s mi. Sau khi khai bo bn c th s dng chng nh bt k cc hng s no khc, v d
circle = cout << NEWLINE; 2 * PI * r;

Trong thc t vic duy nht m trnh dch lm khi n tm thy mt ch th #define l thay th cc tn hng ti bt k ch no chng xut hin (nh trong v d trc, PI, NEWLINE hay WIDTH) bng gi tr m chng c nh ngha. V vy cc hng s #define c coi l cc hng s macro Ch th #define khng phi l mt lnh thc thi, n l ch th tin x l (preprocessor), l l do trnh dch coi c dng l mt ch th v dng khng cn kt thc bng du chm phy. Nu bn thm du chm phy vo cui dng, n s c coi l mt phn ca gi tr nh ngha hng.

Khai bo cc hng (const)


Vi tin t const bn c th khai bo cc hng vi mt kiu xc nh nh l bn lm vi mt bin
const int const to const zip = 12440; char width tab = = 100; '\t';

Trong trng hp kiu khng c ch r (nh trong v d cui) trnh dch s coi n l kiu int.

Bi 1.3: Cc ton t
Qua bi trc chng ta bit n s tn ti ca cc bin v cc hng. Trong C++, thao tc vi chng ta s dng cc ton t, l cc t kho v cc du khng c trong bng ch ci nhng li c trn hu ht cc bn phm trn th gii. Hiu bit v chng l rt quan trng v y l mt trong nhng thnh phn c bn ca ngn ng C++. Ton t gn (=). Ton t gn dng gn mt gi tr no cho mt bin
a = 5;

gn gi tr nguyn 5 cho bin a. V tri bt buc phi l mt bin cn v phi c th l bt k hng, bin hay kt qu ca mt biu thc. Cn phi nhn mnh rng ton t gn lun c thc hin t tri sang phi v khng bao gi o ngc
a = b;

gn gi tr ca bin a bng gi tr ang cha trong bin b. Ch rng chng ta ch gn gi tr ca b cho a v s thay i ca b sau s khng nh hng n gi tr ca a. Mt thuc tnh ca ton t gn trong C++ gp phn gip n vt ln cc ngn ng lp trnh khc l vic cho php v phi c th cha cc php gn khc. V d: 9

a = 2 + (b = 5);

tng ng vi
b a = 2 + b; = 5;

V vy biu thc sau cng hp l trong C++ a = b = c = 5; gn gi tr 5 cho c ba bin a, b v c Cc ton t s hc ( +, -, *, /, % ) Nm ton t s hc c h tr bi ngn ng l: + cng - tr * nhn / chia % ly phn d (trong php chia) Th t thc hin cc ton t ny cng ging nh chng c thc hin trong ton hc. iu duy nht c v hi l i vi bn l php ly phn d, k hiu bng du phn trm (%). y chnh l php ton ly phn d trong php chia hai s nguyn vi nhau. V d, nu a = 11 % 3;, bin a s mang gi tr 2 v 11 = 3*3 +2. Cc ton t gn phc hp (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) Mt c tnh ca ngn ng C++ lm cho n ni ting l mt ngn ng sc tch chnh l cc ton t gn phc hp cho php chnh sa gi tr ca mt bin vi mt trong nhng ton t c bn sau:
value += increase; tng ng vi value = value + a -= 5; tng ng vi a = a a /= b; tng ng vi a = a price *= units + 1; tng ng vi price = price * (units + 1); increase; 5; / b;

v tng t cho tt c cc ton t khc. Tng v gim. Mt v d khc ca vic tit kim khi vit m lnh l ton t tng (++) v gim (--). Chng tng hoc gim gi tr cha trong mt bin i 1. Chng tng ng vi +=1 hoc -=1. V vy, cc dng sau l tng ng:
a++; a+=1; a=a+1;

Mt tnh cht ca ton t ny l n c th l tin t hoc hu t, c ngha l c th vit trc tn bin (++a) hoc sau (a++) v mc d trong hai biu thc rt n gin n c cng ngha nhng trong cc thao tc khc khi m kt qu ca vic tng hay gim c s dng trong mt biu thc th 10

chng c th c mt khc bit quan trng v ngha: Trong trng hp ton t c s dng nh l mt tin t (++a) gi tr c tng trc khi biu thc c tnh v gi tr tng c s dng trong biu thc; trong trng hp ngc li (a++) gi tr trong bin a c tng sau khi tnh ton. Hy ch s khc bit : V d 1
B=3; A=++B; // A is 4, B is 4

V d 2
B=3; A=B++; // A is 3, B is 4

Cc ton t quan h ( ==, !=, >, <, >=, <= ) c th so snh hai biu thc vi nhau chng ta c th s dng cc ton t quan h. Theo chun ANSI-C++ th gi tr ca thao tc quan h ch c th l gi tr logic - chng ch c th c gi tr true hoc false, tu theo biu thc kt qu l ng hay sai. Sau y l cc ton t quan h bn c th s dng trong C++ == Bng != Khc > Ln hn < Nh hn > = Ln hn hoc bng < = Nh hn hoc bng V d: s tr gi tr false s tr gi tr true tt nhin thay v s dng cc s, chng ta c th s dng bt c biu thc no. Cho a=2, b=3 v c=6 (a*b >= c) s tr gi tr true. (b+4 < a*c) s tr gi tr false
(7 == 5) (6 >= 6)

Cn ch rng = (mt du bng) lf hon ton khc vi == (hai du bng). Du u tin l mt ton t gn ( gn gi tr ca biu thc bn phi cho bin bn tri) v du cn li (==) l mt ton t quan h nhm so snh xem hai biu thc c bng nhau hay khng. Trong nhiu trnh dch c trc chun ANSI-C++ cng nh trong ngn ng C, cc ton t quan h khng tr v gi tr logic true hoc false m tr v gi tr int vi 0 tng ng vi false cn gi tr khc 0 (thng l 1) th tng ng vi true. Cc ton t logic ( !, &&, || ). Ton t ! tng ng vi ton t logic NOT, n ch c mt i s pha bn phi v vic duy nht m n lm l i ngc gi tr ca i s t true sang false hoc ngc li. V d: !(5 == 5) tr v false v biu thc bn phi (5 == 5) c gi trtrue. !(6 <= 4) tr v true v (6 <= 4)c gi tr false. !true tr v false. !false tr v true. 11

Ton t logic && v || c s dng khi tnh ton hai biu thc ly ra mt kt qu duy nht. Chng tng ng vi cc ton t logic AND v OR. Kt qu ca chng ph thuc vo mi quan h ca hai i s: i s th nht i s th haiKt quKt qu a && b a || b a b true true true true true false false true false true false true false false false false V d:
( (5 == 5) && (3 > 6) ) tr v false ( true ( (5 == 5) || (3 > 6)) tr v true ( true || false ). && false ).

Ton t iu kin ( ? ). Ton t iu kin tnh ton mt biu thc v tr v mt gi tr khc tu thuc vo biu thc l ng hay sai. Cu trc ca n nh sau:
condition ? result1 : result2

Nu condition l true th gi tr tr v s l result1, nu khng gi tr tr v l result2. 7==5 ? 4 : 3 tr v 3 v 7 khng bng 5. 7==5+2 ? 4 : 3 tr v 4 v 7 bng 5+2. 5>3 ? a : b tr v a, v 5 ln hn 3. a>b ? a : b tr v gi tr ln hn, a hoc b. Cc ton t thao tc bit ( &, |, ^, ~, <<, >> ). Cc ton t thao tc bit thay i cc bit biu din mt bin, c ngha l thay i biu din nh phn ca chng ton t asm M t & AND Logical AND | OR Logical OR ^ XOR Logical exclusive OR ~ NOT o ngc bit << SHL Dch bit sang tri >> SHR Dch bit sang phi Cc ton t chuyn i kiu Cc ton t chuyn i kiu cho php bn chuyn i d liu t kiu ny sang kiu khc. C vi cch lm vic ny trong C++, cch c bn nht c tha k t ngn ng C l t trc biu thc cn chuyn i tn kiu d liu c bc trong cp ngoc n (), v d:
int float i = (int) f; f = i; 3.14;

12

on m trn chuyn s thp phn 3.14 sang mt s nguyn (3). y, ton t chuyn i kiu l (int). Mt cch khc lm iu ny trong C++ l s dng cc constructors ( mt s sch thut ng ny c dch l cu t nhng ti thy n c v khng xui tai lm) thay v dng cc ton t : t trc biu thc cn chuyn i kiu tn kiu mi v bao bc biu thc gia mt cp ngoc n.
i = int ( f );

C hai cch chuyn i kiu u hp l trong C++. Thm vo ANSI-C++ cn c nhng ton t chuyn i kiu mi c trng cho lp trnh hng i tng. sizeof() Ton t ny c mt tham s, c th l mt kiu d liu hay l mt bin v tr v kch c bng byte ca kiu hay i tng .
a = sizeof (char);

a s mang gi tr 1 v kiu char lun c kch c 1 byte trn mi h thng. Gi tr tr v ca sizeof l mt hng s v vy n lun lun c tnh trc khi chng trnh thc hin. Cc ton t khc Trong C++ cn c mt s cc ton t khc, nh cc ton t lin quan n con tr hay lp trnh hng i tng. Chng s c ni n c th trong cc phn tng ng.

Th t u tin ca cc ton t
Khi vit cc biu thc phc tp vi nhiu ton hng cc bn c th t hi ton hng no c tnh trc, ton hng no c tnh sau. V d nh trong biu thc sau:
a = 5 + 7 % 2

c th c hai cch hiu sau:


a = 5 + (7 % a = (5 + 7) % 2 vi kt qu l 0 2)

vi

kt

qu

6,

hoc

Cu tr li ng l biu thc u tin. V nguyn nhn ni trn, ngn ng C++ thit lp mt th t u tin gia cc ton t, khng ch ring cc ton t s hc m tt c cc ton t c th xut hin trong C++. Th t u tin ca chng c lit k trong bng sau theo th t t cao xung thp. Th t Ton t M t :: 1 scope () [ ] -> . sizeof 2 ++ -3 tng/gim ~ o ngc bit ! NOT & * Ton t con tr 13 Associativity Tri Tri Phi

(type) + -

4 5 6 7 8 9 10 11 12 13

* / % + << >> < <= > >= == != & ^ | && || ?:

Chuyn i kiu Dng hoc m Ton t s hc Ton t s hc Dch bit Ton t quan h Ton t quan h Ton t thao tc bit Ton t logic Ton t iu kin gn

Tri Tri Tri Tri Tri Tri Tri Phi Phi Tri

= += -= *= /= %= Ton t >>= <<= &= ^= |= ,

Du phy

Associativity nh ngha trong trng hp c mt vi ton t c cng th t u tin th ci no s c tnh trc, ton t pha xa nht bn phi hay l xa nht bn tri. Nu bn mun vit mt biu thc phc tp m li khng chc lm v th t u tin ca cc ton t th nn s dng cc ngoc n. Cc bn nn thc hin iu ny v n s gip chng trnh d c hn.

14

Bi 1.4: Giao tip vi console.


Console l giao din c bn ca my tnh. Bn phm l thit b vo c bn cn mn hnh l thit b ra c bn. Trong th vin iostream ca C++, cc thao tc vo ra c bn ca mt chng trnh c h tr bi hai dng d liu : cin nhp d liu v cout xut. Thm vo , cn c cerr v clog l hai dng d liu dng hin th cc thng bo li trn thit b ra chun (thng l mn hnh) hoc ra mt file. Thng thng cout c gn vi mn hnh cn cin c gn vi bn phm. S dng hai dng d liu ny bn s c th giao tip vi ngi s dng v bn c th hin th cc thng bo ln mn hnh cng nh nhn d liu t bn phm.

Xut d liu (cout)


Dng cout c s dng vi ton t qu ti << (overloaded - bn s hiu r hn v thut ng ny trong phn lp trnh hng i tng)
cout << "Output sentence"; // Hin th Output sentence ln mn hnh cout << 120; // Hin th s 120 ln mn hnh cout << x; // Hin th ni dung bin x ln mn hnh

Ton t << c gi l ton t chn v n chn d liu i sau n vo dng d liu ng trc. Trong v d trn n chn chui "Output sentence", hng s 120 v bin x vo dng d liu ra cout.Ch rng dng u tin chng ta s dng du ngoc kp v l mt chui k t. Khi chng ta mun s dng cc hng xu k t ta phi t chng trong cp du ngoc kp chng c th c phn bit vi cc bin. V d, hai lnh sau y l hon ton khc nhau:
cout << "Hello"; cout << Hello; // Hin th Hello ln mn hnh // Hin th ni dung ca bin Hello ln mn hnh

Ton t chn (<<) c th c s dng nhiu ln trong mt cu lnh:


cout << "Hello, " << "I am " << "a C++ sentence";

Cu lnh trn s in thng bo Hello, I am a C++ sentence ln mn hnh. S tin li ca vic s dng lp li ton t chn (<<) th hin r khi chng ta mun hin th nhiu bin v hng hn l ch mt bin:
cout << "Hello, I am " << age << " years old and my email address is " << email_add; Cn phi nhn mnh rng cout khng nhy xung dng sau khi xut d liu, v vy hai cu lnh sau : cout << "This cout << "This is another sentence."; is a sentence.";

s c hin th trn mn hnh:


This is a sentence.This is another sentence.

Bi vy khi mun xung dng chng ta phi s dng k t xung dng, trong C++ l \n:
cout << "First cout << "Second sentence.\nThird sentence."; sentence.\n ";

s vit ra mn hnh nh sau:

15

First Second Third sentence.

sentence. sentence.

Thm vo , xung dng bn c th s dng tham s endl. V d


cout << "First cout << "Second sentence." << endl; sentence." << endl;

s in ra mn hnh:
First Second sentence. sentence.

Tham s endl c mt tc dng c bit khi n c dng vi cc dng d liu s dng b m: cc b m s c flushed ( chuyn ton b thng tin t b m ra dng d liu). Tuy nhin, theo mc nh cout khng s dng b m.

Nhp d liu (cin).


Thao tc vo chun trong C++ c thc hin bng cch s dng ton t qu ti >> vi dng cin. Theo sau ton t ny l bin s lu tr d liu c c vo. V d:
int cin >> age; age;

khai bo bin age c kiu int v i nhp d liu t cin (bn phm) lu tr n trong bin kiu nguyn ny. ch bt u s l d liu nhp t bn phm sau khi phm Enter c g. V vy d bn ch nhp mt k t th cin vn s kin nhn ch cho n khi bn g phm Enter.
cin // i/o example #include <iostream.h> int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; } Please enter an integer value: The value you entered is 702 and double is 1404. 702 its

Ngi s dng chng trnh c th l mt trong nhng nguyn nhn gy ra li trong mt chng trnh n gin s dng cin (nh chng trnh trn). Trong khi bn mun nhn mt s nguyn th ngi s dng li nhp vo tn ca h (l mt xu k t). Kt qu l chng trnh s chy sai v khng phi l nhng g m chng trnh mong i t ngi dng. Bi vy khi bn s dng d liu nhp vo t cin bn phi tin chc 16

rng ngi dng s hon ton hp tc v rng anh ta s khng nhp tn ca mnh khi chng trnh yu cu nhp s nguyn. Sau ny, khi nghin cu vic s dng cc xu k t chng ta s xem xt cc gii php kh thi gii quyt cc li loi ny. Bn c th dng cin nhp mt lc nhiu d liu t ngi dng:
cin >> a >> b;

tng ng vi
cin cin >> b; >> a;

Trong c hai trng hp ngi s dng phi cung cp hai d liu, mt cho bin a v mt cho bin b v c ngn cch bi mt du trng hp l: mt du cch, du tab hay k t xung dng. Trong trng hp kiu khng c ch r (nh trong v d cui) trnh dch s coi n l kiu int.

17

Bi 2.1 Cc cu trc iu khin.


Mt chng trnh thng khng ch bao gm cc lnh tun t ni tip nhau. Trong qu trnh chy n c th r nhnh hay lp li mt on m no . lm iu ny chng ta s dng cc cu trc iu khin. Cng vi vic gii thiu cc cu trc iu khin chng ta cng s phi bit ti mt khi nim mi: khi lnh, l mt nhm cc lnh c ngn cch bi du chm phy (;) nhng c gp trong mt khi gii hn bi mt cp ngoc nhn: { v }. Hu ht cc cu trc iu khin m chng ta s xem xt trong chng ny cho php s dng mt lnh n hay mt khi lnh lm tham s, tu thuc vo chng ta c t n trong cp ngoc nhn hay khng.

Cu trc iu kin: if v else


Cu trc ny c dng khi mt lnh hay mt khi lnh ch c thc hin khi mt iu kin no tho mn. Dng ca n nh sau:
if (condition) statement

trong condition l biu thc s c tnh ton. Nu iu kin l true, statement c thc hin. Nu khng statement b b qua (khng thc hin) v chng trnh tip tc thc hin lnh tip sau cu trc iu kin. V d, on m sau y s vit x is 100 ch khi bin x cha gi tr 100:
if (x == 100) cout << "x is 100";

Nu chng ta mun c hn mt lnh c thc hin trong trng hp condition l true chng ta c th ch nh mt khi lnh bng cch s dng mt cp ngoc nhn { }:
if (x == 100) {

cout << "x is "; cout << x;

Chng ta cng c th ch nh iu g s xy ra nu iu kin khng c tho mn bng cch su dng t kho else. N c s dng cng vi if nh sau:
if (condition) statement1 else statement2

18

V d:
if (x == 100) cout else cout << "x is not 100"; << "x is 100";

Cu trc if + else c th c mc ni kim tra nhiu gi tr. V d sau y s kim tra xem gi tr cha trong bin x l dng, m hay bng khng.
if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0";

Cc cu trc lp
Mc ch ca cc vng lp l lp li mt thao tc vi mt s ln nht nh hoc trong khi mt iu kin no cn tho mn. Vng lp while . Dng ca n nh sau:
while (expression) statement

v chc nng ca n n gin ch l lp li statement khi iu kin expression cn tho mn. V d, chng ta s vit mt chng trnh m ngc s dng vo lp while:
// custom countdown using while Enter the starting number #include <iostream.h> 8, 7, 6, 5, 4, 3, 2, 1, FIRE! int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!"; return 0; } > 8

19

Khi chng trnh chy ngi s dng c yu cu nhp vo mt s m ngc. Sau , khi vng lp while bt u nu s m ngi dng nhp vo tho mn iu kin iu kin n>0 khi lnh s c thc hin mt s ln khng xc nh chng no iu kin (n>0) cn c tho mn. Chng ta cn phi nh rng vng lp phi kt thc mt im no , v vy bn trong vng lp chng ta phi cung cp mt phng thc no buc condition tr thnh sai nu khng th n s lp li mi mi. Trong v d trn vng lp phi c lnh --n; lm cho condition tr thnh sai sau mt s ln lp. Vng lp do-while Dng thc:
do statement while (condition);

Chc nng ca n l hon ton ging vng lp while ch tr c mt iu l iu kin iu khin vng lp c tnh ton sau khi statement c thc hin, v vy statement s c thc hin t nht mt ln ngay c khi condition khng bao gi c tho mn. V d, chng trnh di y s vit ra bt k s no m bn nhp vo cho n khi bn nhp s 0.
// number echoer #include <iostream.h> int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; } Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0

Vng lp do-while thng c dng khi iu kin kt thc vng lp nm trong vng lp, nh trong v d trn, s m ngi dng nhp vo l iu kin kim tra kt thc vng lp. Nu bn khng nhp s 0 trong v d trn th vng lp s khng bao gi chm dt. Vng lp for . Dng thc:
for (initialization; condition; increase) statement;

v chc nng chnh ca n l lp li statement chng no condition cn mang gi tr ng, nh trong vng lp while. Nhng thm vo , for cung cp ch dnh cho lnh khi to v lnh tng. V vy vng lp ny c thit k c bit lp li mt hnh ng vi mt s ln xc nh. Cch thc hot ng ca n nh sau: 1, initialization c thc hin. Ni chung n t mt gi kh ban u cho bin iu khin. Lnh ny c thc hin ch mt ln. 2, condition c kim tra, nu n l ng vng lp tip tc cn nu khng vng lp kt thc v statement c b qua. 20

3, statement c thc hin. N c th l mt lnh n hoc l mt khi lnh c bao trong mt cp ngoc nhn. 4, Cui cng, increase c thc hin tng bin iu khin v vng lp quay tr li bc 2. Sau y l mt v d m ngc s dng vng for.
// countdown using a for loop #include <iostream.h> int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Phn khi to v lnh tng khng bt buc phi c. Chng c th c b qua nhng vn phi c du chm phy ngn cch gia cc phn. V vy, chng ta c th vit for (;n<10;) hoc for (;n<10;n++). Bng cch s dng du phy, chng ta c th dng nhiu lnh trong bt k trng no trong vng for, nh l trong phn khi to. V d chng ta c th khi to mt lc nhiu bin trong vng lp:
for ( n=0, i=100 ; n!=i ; n++, i-- ) { // ci g y cng c... }

Vng lp ny s thc hin 50 ln nu nh n v i khng b thay i trong thn vng lp:

Cc lnh r nhnh v lnh nhy


Lnh break. S dng break chng ta c th thot khi vng lp ngay c khi iu kin n kt thc cha c tho mn. Lnh ny c th c dng kt thc mt vng lp khng xc nh hay buc n phi kt thc gia chng thay v kt thc mt cch bnh thng. V d, chng ta s dng vic m ngc trc khi n kt thc:
// break loop example #include <iostream.h> int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { 10, 9, 8, aborted! 7, 6, 5, 4, countdown

21

} } return 0; }

cout << "countdown aborted!"; break;

Lnh continue. Lnh continue lm cho chng trnh b qua phn cn li ca vng lp v nhy sang ln lp tip theo. V d chng ta s b qua s 5 trong phn m ngc:
// break loop example #include <iostream.h> int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!"; return 0; } 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

Lnh goto. Lnh ny cho php nhy v iu kin ti bt k im no trong chng trnh. Ni chung bn nn trnh dng n trong chng trnh C++. Tuy nhin chng ta vn c mt v d dng lnh goto m ngc:
// goto loop example #include <iostream.h> int main () { int n=10; loop: ; cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Hm exit. Mc ch ca exit l kt thc chng trnh v tr v mt m xc nh. Dng thc ca n nh sau


void exit (int exit code);

c dng bi mt s h iu hnh hoc c th c dng bi cc chng trnh gi. Theo quy c, m tr v 0 c ngha l chng trnh kt thc bnh thng cn cc gi tr khc 0 c ngha l c li.
exit code

Cu trc la chn: switch.


C php ca lnh switch hi c bit mt cht. Mc ch ca n l kim tra mt vi gi tr hng cho mt biu thc, tng t vi nhng g chng ta lm u bi ny khi lin kt mt vi lnh if v else if vi nhau. Dng thc ca n nh sau:
switch (expression) { case constant1:

22

block of instructions 1 break; case constant2: block of instructions 2 break; . . . default: default block of instructions }

N hot ng theo cch sau: switch tnh biu thc v kim tra xem n c bng constant1 hay khng, nu ng th n thc hin block of instructions 1 cho n khi tm thy t kho break, sau nhy n phn cui ca cu trc la chn switch. Cn nu khng, switch s kim tra xem biu thc c bng constant2 hay khng. Nu ng n s thc hin block of instructions 2 cho n khi tm thy t kho break. Cui cng, nu gi tr biu thc khng bng bt k hng no c ch nh trn (bn c th ch nh bao nhiu cu lnh case tu thch), chng trnh s thc hin cc lnh trong phn default: nu n tn ti v phn ny khng bt buc phi c. Hai on m sau l tng ng:

v d switch
switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; }

if-else tng ng
if (x == 1) { cout << "x is 1"; } else if (x == 2) { cout << "x is 2"; } else { cout << "value of x unknown"; }

Ti ni trn rng cu trc ca lnh switch hi c bit. Ch s tn ti ca lnh break cui mi khi lnh. iu ny l cn thit v nu khng th sau khi thc hin block of instructions 1 chng trnh s khng nhy n cui ca lnh switch m s thc hin cc khi lnh tip theo cho n khi n tm thy lnh break u tin. iu ny khin cho vic t cp ngoc nhn { } trong mi trng hp l khng cn thit v c th c dng khi bn mun thc hin mt khi lnh cho nhiu trng hp khc nhau, v d:
switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }

23

Ch rng lnh switch ch c th c dng so snh mt biu thc vi cc hng. V vy chng ta khng th t cc bin (case (n*2):) hay cc khong (case (1..3):) v chng khng phi l cc hng hp l. Nu bn cn kim tra cc khong hay nhiu gi tr khng phi l hng s hy kt hp cc lnh if v else if.

Bi 2.2 Hm (I)
Hm l mt khi lnh c thc hin khi n c gi t mt im khc ca chng trnh. Dng thc ca n nh sau:
type name ( argument1, argument2, ...) statement

trong : type l kiu d liu c tr v ca hm name l tn gi ca hm. arguments l cc tham s (c nhiu bao nhiu cng c tu theo nhu cu). Mt tham s bao gm tn kiu d liu sau l tn ca tham s ging nh khi khai bo bin (v d int x) v ng vai tr bn trong hm nh bt k bin no khc. Chng dng truyn tham s cho hm khi n c gi. Cc tham s khc nhau c ngn cch bi cc du phy. statement l thn ca hm. N c th l mt lnh n hay mt khi lnh. Di y l v d u tin v hm:
// function example #include <iostream.h> int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } The result is 8

c th hiu c on m ny, trc ht hy nh li nhng iu ni bi u tin: mt chng trnh C++ lun bt u thc hin t hm main. V vy chng ta bt u t y. Chng ta c th thy hm main bt u bng vic khai bo bin z kiu int. Ngay sau l mt li gi ti hm addition. Nu chng ta s thy s tng t gia cu trc ca li gi hm vi khai bo ca hm:

24

Cc tham s c vai tr tht r rng. Bn trong hm main chng ta gi hm addition v truyn hai gi tr: 5 v 3 tng ng vi hai tham s int a v int b c khai bo cho hm addition. Vo thi im hm c gi t main, quyn iu khin c chuyn sang cho hm addition. Gi tr ca c hai tham s (5 v 3) c copy sang hai bin cc b int a v int b bn trong hm. Dng lnh sau:
return (r);

kt thc hm addition, v tr li quyn iu khin cho hm no gi n (main) v tip tc chng trnh ci im m n b ngt bi li gi n addition. Nhng thm vo , gi tr c dng vi lnh return (r) chnh l gi tr c tr v ca hm.\

Gi tr tr v bi mt hm chnh l gi tr ca hm khi n c tnh ton. V vy bin z s c c gi tr c tr v bi addition (5, 3), l 8. Phm vi hot ng ca cc bin [nhc li] Bn cn nh rng phm vi hot ng ca cc bin khai bo trong mt hm hay bt k mt khi lnh no khc ch l hm hay khi lnh v khng th s dng bn ngoi chng. V d, trong chng trnh v d trn, bn khng th s dng trc tip cc bin a, b hay r trong hm main v chng l cc bin cc b ca hm addition. Thm vo bn cng khng th s dng bin z trc tip bn trong hm addition v n lm bin cc b ca hm main. Tuy nhin bn c th khai bo cc bin ton cc c th s dng chng bt k u, bn trong hay bn ngoi bt k hm no. lm vic ny bn cn khai bo chng bn ngoi mi hm hay cc khi lnh, c ngha l ngay trong thn chng trnh. y l mt v d khc v hm:
// function example #include <iostream.h> int subtraction (int a, int b) { int r; r=a-b; return (r); } The first The second The third The fourth result is result result result 6 is is is 5 5 2

25

int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << '\n'; cout << "The second result is subtraction (7,2) << '\n'; cout << "The third result is subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << '\n'; return 0; }

z << " " << <<

z <<

Trong trng hp ny chng ta to ra hm subtraction. Chc nng ca hm ny l ly hiu ca hai tham s ri tr v kt qu. Tuy nhin, nu phn tch hm main cc bn s thy chng trnh vi ln gi n hm subtraction. Ti s dng vi cch gi khc nhau cc bn thy cc cch khc nhau m mt hm c th c gi. c hiu cn k v d ny bn cn nh rng mt li gi n mt hm c th hon ton c thay th bi gi tr ca n. V d trong lnh gi hm u tin :
z = cout << "The first result is " << z; subtraction (7,2);

Nu chng ta thay li gi hm bng gi tr ca n ( l 5), chng ta s c:


z = cout << "The first result is " << z; 5;

Tng t nh vy
cout << "The second result is " << subtraction (7,2);

cng cho kt qu ging nh hai dng lnh trn nhng trong trng hp ny chng ta gi hm subtraction trc tip nh l mt tham s ca cout. Chng ta cng c th vit:
cout << "The second result is " << 5;

v 5 l kt qu ca subtraction (7,2). Cn vi lnh


cout << "The third result is " << subtraction (x,y);

iu mi m duy nht y l cc tham s ca subtraction l cc bin thay v cc hng. iu ny l hon ton hp l. Trong trng hp ny gi tr c truyn cho hm subtraction l gi tr ca x and y. Trng hp th t cng hon ton tng t. Thay v vit 26

z = 4 + subtraction (x,y);

chng ta c th vit:
z = subtraction (x,y) + 4;

cng hon ton cho kt qu tng ng. Ch rng du chm phy c t cui biu thc ch khng cn thit phi t ngay sau li gi hm.

Cc hm khng kiu. Cch s dng void.


Nu bn cn nh c php ca mt li khai bo hm:
type name ( argument1, argument2 ...) statement

bn s thy r rng rng n bt u vi mt tn kiu, l kiu d liu s c hm tr v bi lnh return. Nhng nu chng ta khng mun tr v gi tr no th sao ? Hy tng tng rng chng ta mun to ra mt hm ch hin th mt thng bo ln mn hnh. N khng cn tr v mt gi tr no c, hn na cng khng cn nhn tham s no ht. V vy ngi ta ngh ra kiu d liu void trong ngn ng C. Hy xem xt chng trnh sau:
// void function example #include <iostream.h> void dummyfunction (void) { cout << "I'm a function!"; } int main () { dummyfunction (); return 0; } I'm a function!

T kho void trong phn danh sch tham s c ngha l hm ny khng nhn mt tham s no. Tuy nhin trong C++ khng cn thit phi s dng void lm iu ny. Bn ch n gin s dng cp ngoc n ( ) l xong. Bi v hm ca chng ta khng c mt tham s no, v vy li gi hm dummyfunction s l :
dummyfunction ();

Hai du ngoc n l cn thit cho trnh dch hiu l mt li gi hm ch khng phi l mt tn bin hay bt k du hiu no khc.

Bi 2.3

Hm (II)
27

Truyn tham s theo tham s gi tr hay tham s bin.


Cho n nay, trong tt c cc hm chng ta bit, tt c cc tham s truyn cho hm u c truyn theo gi tr. iu ny c ngha l khi chng ta gi hm vi cc tham s, nhng g chng ta truyn cho hm l cc gi tr ch khng phi bn thn cc bin. V d, gi s chng ta gi hm addition nh sau:
int x=5, z = addition ( x , y ); y=3, z;

Trong trng hp ny khi chng ta gi hm addition th cc gi tr 5 and 3 c truyn cho hm, khng phi l bn thn cc bin.

n y cc bn c th hi ti: Nh vy th sao, c nh hng g u ? iu ng ni y l khi cc bn thay i gi tr ca cc bin a hay b bn trong hm th cc bin x v y vn khng thay i v chng u c c truyn cho hm ch c gi tr ca chng c truyn m thi. Hy xt trng hp bn cn thao tc vi mt bin ngoi bn trong mt hm. V vy bn s phi truyn tham s di dng tham s bin nh trong hm duplicate trong v d di y:
// passing parameters by reference #include <iostream.h> void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; } x=2, y=6, z=14

iu u tin lm bn ch l trong khai bo ca duplicate theo sau tn kiu ca mi tham s u l du v (&), bo hiu rng cc tham s ny c truyn theo tham s bin ch khng phi tham s gi tr. Khi truyn tham s di dng tham s bin chng ta ang truyn bn thn bin v bt k s thay i no m chng ta thc hin vi tham s bn trong hm s nh hng trc tip n bin .

28

Trong v d trn, chng ta lin kt a, b v c vi cc tham s khi gi hm (x, y v z) v mi s thay i vi a bn trong hm s nh hng n gi tr ca x v hon ton tng t vi b v y, c v z. Kiu khai bo tham s theo dng tham s bin s dng du v (&) ch c trong C++. Trong ngn ng C chng ta phi s dng con tr lm vic tng t nh th. Truyn tham s di dng tham s bin cho php mt hm tr v nhiu hn mt gi tr. V d, y l mt hm tr v s lin trc v lin sau ca tham s u tin.
// more than one returning value #include <iostream.h> void prevnext next) { prev = x-1; next = x+1; } (int x, int& prev, int& Previous=99, Next=101

int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; }

Gi tr mc nh ca tham s.
Khi nh ngha mt hm chng ta c th ch nh nhng gi tr mc nh s c truyn cho cc i s trong trng hp chng b b qua khi hm c gi. lm vic ny n gin ch cn gn mt gi tr cho i s khi khai bo hm. Nu gi tr ca tham s vn c ch nh khi gi hm th gi tr mc nh s b b qua. V d:
// default values in functions #include <iostream.h> int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; 6 5

29

cout << divide (20,4); return 0;

Nhng chng ta thy trong thn chng trnh, c hai li gi hm divide. Trong lnh u tin:
divide (12)

chng ta ch dng mt tham s nhng hm divide cho php n hai. Bi vy hm divide s t cho tham s th hai gi tr bng 2 v l gi tr mc nh ca n (ch phn khai bo hm c kt thc bi int b=2). V vy kt qu s l 6 (12/2). Trong lnh th hai:
divide (20,4)

c hai tham s, bi vy gi tr mc nh s c b qua. Kt qu ca hm s l 5 (20/4).

Qu ti cc hm.
Hai hm c th c cng tn nu khai bo tham s ca chng khc nhau, iu ny c ngha l bn c th t cng mt tn cho nhiu hm nu chng c s tham s khc nhau hay kiu d liu ca cc tham s khc nhau (hay thm ch l kiu d liu tr v khc nhau). V d:
// overloaded function #include <iostream.h> int divide (int a, int b) { return (a/b); } float divide (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << divide (x,y); cout << "\n"; cout << divide (n,m); return 0; } 2 2.5

Trong v d ny chng ta nh ngha hai hm c cng tn nhng mt hm dng hai tham s kiu int v hm cn li dng kiu float. Trnh bin dch s bit cn phi gi hm no bng cch phn tch kiu tham s khi hm c gi. n gin ti vit c hai hm u c m lnh nh nhau nhng iu ny khng bt buc. Bn c th xy dng hai hm c cng tn nhng hot ng hon ton khc nhau. 30

Cc hm inline.
Ch th inline c th c t trc khao bo ca mt hm ch r rng li gi hm s c thay th bng m lnh ca hm khi chng trnh c dch. Vic ny tng ng vi vic khai bo mt macro, li ch ca n ch th hin vi cc hm rt ngn, tc chy chng trnh s c ci thin v n khng phi gi mt th tc con. Cu trc ca n nh sau:
inline type name ( arguments ... ) { instructions ... }

li gi hm cng nh bt k mt hm no khc. Khng cn thit phi t t kho inline trong lnh gi, ch cn trong li khai bo hm l .

qui.
Cc hm c th gi chnh n. iu ny c th c ch vi mt s tc v nh l mt s phng php sp xp hay tnh giai tha ca mt s. V d, tnh giai tha ca mt s (n), cng thc ton hc ca n nh sau:
n! = n * (n-1) * (n-2) * (n-3) ... * 1

v mt hm qui tnh ton s nh sau:


// factorial calculator #include <iostream.h> long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } int main () { long l; cout << "Type a number: "; cin >> l; cout << "!" << l << " = " << factorial (l); return 0; } Type !9 = 362880 a number: 9

Ch trong hm factorial chng ta c th lnh gi chnh n nhng ch khi tham s ln hn 1, nu khng th hm s thc hin mt vng lp v hn v sau khi n 0 n s tip tc nhn c nhng s m. Hm ny c mt hn ch l kiu d liu m n dng (long) khng cho php tnh giai tha qu 12!.

Khai bo mu cho hm.


Cho n gi chng ta hon ton phi nh ngha hm trc lnh gi u tin n n, m thng l trong main, v vy hm main lun phi nm cui chng trnh. Nu bn th lp li mt vi v d v hm trc 31

y nhng th t hm main trc bt k mt hm c gi t n, bn gn nh chc chn s nhn c thng bo li. Nguyn nhn l mt hm phi c khai bo trc khi n c gi nh nhng g chng ta lm trong tt c cc v d. Nhng c mt cch khc trnh phi vit tt c m chng trnh trc khi chng c th c dng trong main hay bt k mt hm no khc. chnh l khai bo mu cho hm. Cch ny bao gm vic khai bo hm mt cch ngn gn nhng cho trnh dch c th bit cc tham s v kiu d liu tr v ca hm. Dng ca n nh sau:
type name ( argument_type1, argument_type2, ...);

y chnh l phn u ca nh ngha hm, ngoi tr:


N khng c bt k lnh no cho hm. iu ny c ngha l n khng bao gm thn hm vi tt c cc lnh thng c bc trong cp ngoc nhn { }. N kt thc bng du chm phy (;). Trong phn lit k cc tham s ch cn vit kiu ca chng l . Vic vit tn ca cc tham s trong phn khai bo mu l khng bt buc.

V d:
// prototyping #include <iostream.h> void odd (int a); void even (int a); int main () { int i; do { cout << "Type a number: (0 to exit)"; cin >> i; odd (i); } while (i!=0); return 0; } void odd (int a) { if ((a%2)!=0) odd.\n"; else even (a); } void even (int a) { if ((a%2)==0) even.\n"; else odd (a); } Type Number Type Number Type Number Type Number a a a number number number (0 to exit): 9 is odd. (0 to exit): 6 is even. (0 to exit): 1030 is even. (0 to exit): 0

a number is even.

cout

<<

"Number

is

cout

<<

"Number

is

32

V d ny r rng khng phi l mt v d v s hiu qu. Ti chc chn rng cc bn c th nhn c kt qu nh trn ch vi mt na s dng lnh. Tuy nhin n gip cho chng ta thy c vic khai bo mu cc hm l nh th no. Hn na, trong v d ny vic khai bo mu t nht mt hm l bt buc. u tin chng ta thy khai bo mu ca hai hm odd v even:
void void even (int a); odd (int a);

cho php hai hm ny c th c s dng trc khi chng c nh ngha hon chnh. Tuy nhin l do c bit gii thch ti sao chng trnh ny li cn t nht mt hm phi c khi bo mu l trong odd c mt li gi n even v trong even c mt li gi n odd. V vy nu khng c hm no c khai bo trc th li chc chn s xy ra. Rt nhiu lp trnh vin kinh nghim khuyn rng tt c cc hm nn c khai bo mu. cng l li khuyn ca ti, nht l trong trng hp c nhiu hm hoc chng rt di, khi vic khai bo tt c cc hm cng mt ch cho php chng ta bit phi gi cc hm nh th no, v vy tit kim c thi gian.

Bi 3.1

Mng

Mng l mt dy cc phn t c cng kiu c t lin tip trong b nh v c th truy xut n tng phn t bng cch thm mt ch s vo sau tn ca mng. iu ny c ngha l, v d, chng ta c th lu 5 gi tr kiu int m khng cn phi khai bo 5 bin khc nhau.V d, mt mng cha 5 gi tr nguyn kiu int c tn l billy c th c biu din nh sau:

trong mi mt trng biu din mt phn t ca mng, trong trng hp ny l cc gi tr nguyn kiu int. Chng c nh s t 0 n 4 v phn t u tin ca mng lun l 0 bt k di ca n l bao nhiu. Nh bt k bin no khc, mt mng phi c khai bo trc khi c th s dng. Mt khai bo in hnh cho mt mng trong C++ nh sau:
type name [elements];

trong type l mt kiu d liu hp l (int, float...), name l mt tn bin hp l v trng elements ch nh mng s cha bao nhiu phn t V vy, khai bo billy nh trnh by trn chng ta ch cn mt dng n gin nh sau:
int billy [5];

Ch : Trng elements bn trong cp ngoc [] phi l mt gi tr hng khi khai bo mt mng, v mng l mt khi nh tnh c kch c xc nh v trnh bin dch phi c kh nng xc nh xem cn bao nhiu b 33

nh cp pht cho mng trc khi cc lnh c th c thc hin.

Khi to mt mng.
Khi khai bo mt mng vi tm hot ng a phng (trong mt hm), theo mc nh n s khng c khi to, v vy ni dung ca n l khng xc nh cho n khi chng ra lu cc gi tr ln . Nu chng ta khai bo mt mng ton cc (bn ngoi tt c cc hm) n s c khi to v tt c cc phn t c t bng 0. V vy nu chng ta khai bo mng ton cc:

int billy [5];

mi phn t ca billy s c khi to l 0:

Nhng thm vo , khi chng ta khai bo mt mng, chng ta c th gn cc gi tr khi to cho tng phn t ca n. V d:
int billy [5] = { 16, 2, 77, 40, 12071 };

lnh trn s khai bo mt mng nh sau:

S phn t trong mng m chng ta khi to vi cp ngoc nhn { } phi bng s phn t ca mng c khai bo vi cp ngoc vung [ ]. Bi v iu ny c th c coi l mt s lp li khng cn thit nn C++ cho php trng gia cp ngoc vung, kch thc ca mng c xc nh bng s gi tr gia cp ngoc nhn.

Truy xut n cc phn t ca mng.


bt k im no ca chng trnh trong tm hot ng ca mng, chng ta c th truy xut tng phn t ca mng c hay chnh sa nh l i vi mt bin bnh thng. Cu trc ca n nh sau:
name[index]

34

Nh trong v d trc ta c mng billy gm 5 phn t c kiu int, chng ta c th truy xut n tng phn t ca mng nh sau:

V d, lu gi tr 75 vo phn t th ba ca billy ta vit nh sau:


billy[2] = 75;

v, v d, gn gi tr ca phn t th 3 ca billy cho bin a, chng ta vit:


a = billy[2];

V vy, xt v mi phng din, biu thc billy[2] ging nh bt k mt bin kiu int. Ch rng phn t th ba ca billy l billy[2], v mng bt u t ch s 0. V vy, phn t cui cng s l billy[4]. V vy nu chng ta vit billy[5], chng ta s truy xut n phn t th 6 ca mng v vt qu gii hn ca mng. Trong C++, vic vt qu gii hn ch s ca mng l hon ton hp l, tuy nhin n c th gy ra nhng vn thc s kh pht hin bi v chng khng to ra nhng li trong qu trnh dch nhng chng c th to ra nhng kt qu khng mong mun trong qu trnh thc hin. Nguyn nhn ca vic ny s c ni n k hn khi chng ta bt u s dng con tr. Cn phi nhn mnh rng chng ta s dng cp ngoc vung cho hai tc v: u tin l t kch thc cho mng khi khai bo chng v th hai, ch nh ch s cho mt phn t c th ca mng khi xem xt n n.
int billy[5]; billy[2] = 75; // khai bo mt mng mi. // truy xut n mt phn t ca mng.

Mt vi thao tc hp l khc vi mng:


billy[0] billy[a] b = billy[billy[a]] = billy[2] + 5; // v d v mng #include <iostream.h> int billy [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; = = billy a; 75; [a+2];

12206

35

return 0; }

Mng nhiu chiu.


Mng nhiu chiu c th c coi nh mng ca mng, v d, mt mng hai chiu c th c tng tc nh l mt bng hai chiu gm cc phn t c kiu d liu c th v ging nhau.

jimmy

biu din mt mng hai chiu kch thc 3x5 c kiu int. Cch khai bo mng ny nh sau:
int jimmy [3][5];

v, v d, cch truy xut n phn t th hai theo chiu dc v th t theo chiu ngang trong mt biu thc nh sau:
jimmy[1][3]

(hy nh rng ch s ca mng lun bt u t 0). Mng nhiu chiu khng b gii hn bi hai ch s (hai chiu), Chng c th cha bao nhiu ch s ty thch mc d t kh cn phi dng n mng ln hn 3 chiu. Hy th xem xt lng b nh m mt mng c nhiu ch s cn n. V d:
char century [100][365][24][60][60];

gn mt gi tr char cho mi giy trong mt th k, phi cn n hn 3 t gi tr chars! Chng ta s phi cn khong 3GB RAM khai bo n. Mng nhiu chiu thc ra l mt khi nim tru tng v chng ta c th c kt qu tng t vi mng mt chiu bng mt thao tc n gin gia cc ch s ca n:
int jimmy [3][5]; int jimmy [15]; (3 * 5 = 15)

tng

ng

vi

Di y l hai v d vi cng mt kt qu nh nhau, mt s dng mng hai chiu v mt s dng mng mt chiu:
// multidimensional array // pseudo-multidimensional array

36

#include <iostream.h> #define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT][WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); } return 0; }

#include <iostream.h> #define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT * WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n * WIDTH + m]=(n+1)*(m+1); } return 0; }

khng mt chng trnh no vit g ra mn hnh nhng c hai u gn gi tr vo khi nh c tn jimmy theo cch sau:

Chng ta nh ngha hng (#define) n gin ha nhng chnh sa sau ny ca chng trnh, v d, trong trng hp chng ta quyt nh tng kch thc ca mng vi chiu cao l 4 thay v l 3, chng ta ch cn thay i dng:
#define HEIGHT 3

thnh
#define HEIGHT 4

v khng phi c thm s thay i no na i vi chng trnh.

Dng mng lm tham s.


Vo mt lc no c th chng ta cn phi truyn mt mng ti mt hm nh l mt tham s. Trong C++, vic truyn theo tham s gi tr mt khi nh l khng hp l, ngay c khi n c t chc thnh mt mng. Tuy nhin chng ta li c php truyn a ch ca n, vic ny cng to ra kt qu thc t ging thao tc trn nhng li nhanh hn nhiu v hiu qu hn. c th nhn mng l tham s th iu duy nht chng ta phi lm khi khai bo hm l ch nh trong phn tham s kiu d liu c bn ca mng, tn mng v cp ngoc vung trng. V d, hm sau:
void procedure (int arg[])

37

nhn vo mt tham s c kiu "mng ca char" v c tn arg. truyn tham s cho hm ny mt mng c khai bo:
int myarray [40];

ch cn gi hm nh sau:
procedure (myarray);

Di y l mt v d c th
// arrays as parameters #include <iostream.h> void printarray (int arg[], int length) { for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n"; } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); return 0; } 5 2 4 6 8 10 10 15

Nh bn c th thy, tham s u tin (int arg[]) chp nhn mi mng c kiu c bn l int, bt k di ca n l bao nhiu, v vy cn thit phi c tham s th hai bo cho hm ny bit di ca mng m chng ta truyn cho n. Trong phn khai bo hm chng ta cng c th dng tham s l cc mng nhiu chiu. Cu trc ca mng 3 chiu nh sau:
base_type[][depth][depth]

v d, mt hm vi tham s l mng nhiu chiu c th nh sau:


void procedure (int myarray[][3][4])

ch rng cp ngoc vung u tin trng nhng cc cp ngoc sau th khng. Bn lun lun phi lm vy v trnh bin dch C++ phi c kh nng xc nh ln ca cc chiu thm vo ca mng. Mng, c mt chiu v nhiu chiu, khi truyn cho hm nh l mt tham s thng l nguyn nhn gy li cho nhng lp trnh vin thiu kinh nghim. Cc bn nn c bi 3.3. Con tr c th hiu r hn mng hot ng nh th no.

38

Bi 3.2 Xu k t
Trong tt c cc chng trnh chng ta thy cho n gi, chng ta ch s dng cc bin kiu s, ch dng biu din cc s. Nhng bn cnh cc bin kiu s cn c cc xu k t, chng cho php chng ta biu din cc chui k t nh l cc t, cu, on vn bn... Cho n gi chng ta mi ch dng chng di dng hng ch cha quan tm n cc bin c th cha chng. Trong C++ khng c kiu d liu c bn lu cc xu k t. c th tha mn nhu cu ny, ngi ta s dng mng c kiu char. Hy nh rng kiu d liu ny (char) ch c th lu tr mt k t n, bi vy n c dng to ra xu ca cc k t n. V d, mng sau (hay l xu k t):
char jenny [20];

c th lu mt xu k t vi di cc i l 20 k t. Bn c th tng tng n nh sau:

Kch thc cc i ny khng cn phi lun lun dng n. V d, jenny c th lu xu "Hello" hay "Merry christmas". V cc mng k t c th lu cc xu k t ngn hn di ca n, trong C++ c mt quy c kt thc mt ni dung ca mt xu k t bng mt k t null, c th c vit l '\0'. Chng ta c th biu din jenny (mt mng c 20 phn t kiu char) khi lu tr xu k t "Hello" v "Merry Christmas" theo cch sau:

Ch rng sau ni dung ca xu, mt k t null ('\0') c dng bo hiu kt thc xu. Nhng mu xm biu din nhng gi tr khng xc nh.

Khi to cc xu k t.
V nhng xu k t l nhng mng bnh thng nn chng cng nh cc mng khc. V d, nu chng ta mun khi to mt xu k t vi nhng gi tr xc nh chng ta c th lm iu tng t nh vi cc mng khc:
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

Tuy nhin, chng ta c th khi to gi tr cho mt xu k t bng cch khc: s dng cc hng xu k t. Trong cc biu thc chng ta s dng trong cc v d trong cc chng trc cc hng xu k t xut hin vi ln. Chng c biu din trong cp ngoc kp ("), v d: 39

"the result is: "

l mt hng xu k t chng ta s dng mt s ch. Khng ging nh du nhy n (') cho php biu din hng k t, cp ngoc kp ( ") l hng biu din mt chui k t lin tip, v cui chui mt k t null ('\0') lun c t ng thm vo. V vy chng ta c th khi to xu mystring theo mt trong hai cch sau y:
char mystring [] = { char mystring [] = "Hello"; 'H', 'e', 'l', 'l', 'o', '\0' };

Trong c hai trng hp mng (hay xu k t) mystring c khai bo vi kch thc 6 k t: 5 k t biu din Hello cng vi mt k t null. Trc khi tip tc, ti cn phi nhc nh bn rng vic gn nhiu hng nh vic s dng du ngoc kp ( ") ch hp l khi khi to mng, tc l lc khai bo mng. Cc biu thc trong chng trnh nh:
mystring mystring[] = "Hello"; = "Hello";

l khng hp l, c cu lnh di y cng vy:


mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };

Vy hy nh: Chng ta ch c th "gn" nhiu hng cho mt mng vo lc khi to n. Nguyn nhn l mt thao tc gn (=) khng th nhn v tri l c mt mng m ch c th nhn mt trong nhng phn t ca n. Vo thi im khi to mng l mt trng hp c bit, v n khng thc s l mt lnh gn mc d n s dng du bng (=).

Gn gi tr cho xu k t
V v tri ca mt lnh gn ch c th l mt phn t ca mng ch khng th l c mng, chng ta c th gn mt xu k t cho mt mng kiu char s dng mt phng php nh sau:
mystring[0] mystring[1] mystring[2] mystring[3] mystring[4] mystring[5] = '\0'; = = = = = 'H'; 'e'; 'l'; 'l'; 'o';

Nhng r rng y khng phi l mt phng php thc t. gn gi tr cho mt xu k t, chng ta c th s dng lot hm kiu strcpy (string copy), hm ny c nh ngha trong string.h v c th c gi nh sau:
strcpy (string1, string2);

Lnh ny copy ni dung ca string2 sang string1. string2 c th l mt mng, con tr hay mt hng xu k t, bi vy lnh sau y l mt cch ng gn xu hng "Hello" cho mystring: 40

strcpy (mystring, "Hello");

V d:
// setting value to string #include <iostream.h> #include <string.h> int main () { char szMyName [20]; strcpy (szMyName,"J. Soulie"); cout << szMyName; return 0; } J. Soulie

rng chng ta phi include file <string.h> c th s dng hm strcpy. Mc d chng ta lun c th vit mt hm n gin nh hm setstring di y thc hin mt thao tc ging nh strcpy:
// setting value to string #include <iostream.h> void setstring (char szOut [], char szIn []) { int n=0; do { szOut[n] = szIn[n]; n++; } while (szIn[n] != 0); } int main () { char szMyName [20]; setstring (szMyName,"J. Soulie"); cout << szMyName; return 0; } J. Soulie

Mt phng thc thng dng khc gn gi tr cho mt mng l s dng trc tip dng nhp d liu (cin). Trong trng hp ny gi tr ca xu k t c gn bi ngi dng trong qu trnh chng trnh thc hin. Khi cin c s dng vi cc xu k t n thng c dng vi phng thc getline ca n, phng thc ny c th c gi nh sau:
cin.getline ( char buffer[], int length, char delimiter = ' \n');

trong buffer (b m) l a ch ni s lu tr d liu vo (nh l mt mng chng hn), length l di cc i ca b m (kch thc ca mng) v delimiter l k t c dng kt thc vic nhp, mc nh - nu chng ta khng dng tham s ny - s l k t xung dng ('\n'). 41

V d sau y lp li tt c nhng g bn g trn bn phm. N rt n gin nhng l mt v d cho thy bn c th s dng cin.getline vi cc xu k t nh th no:
// cin with strings #include <iostream.h> int main () { char mybuffer [100]; cout << "What's your name? "; cin.getline (mybuffer,100); cout << "Hello " << mybuffer << ".\n"; cout << "Which is your favourite team? "; cin.getline (mybuffer,100); cout << "I like " << mybuffer << " too.\n"; return 0; } What's your name? Juan Hello Juan. Which is your favourite team? Inter Milan I like Inter Milan too.

Ch trong c hai li gi cin.getline chng ta s dng cng mt bin xu (mybuffer). Nhng g chng trnh lm trong li gi th hai n gin l thay th ni dung ca buffer trong li gi c bng ni dung mi. Nu bn cn nh phn ni v giao tip vi, bn s nh rng chng ta s dng ton t >> nhn d liu trc tip t u vo chun. Phng thc ny c th c dng vi cc xu k t thay cho cin.getline. V d, trong chn trnh ca chng ta, khi chng ta mun nhn d liu t ngi dng chng ta c th vit:
cin >> mybuffer;

lnh ny s lm vic nh n c nhng hn ch sau m cin.getline khng c:


N ch c th nhn nhng t n (khng nhn c c cu) v phng thc ny s dng k t trng(bao gm c du cch, du tab v du xung dng) lm du hiu kt thc.. N khng cho php ch nh kch thc cho b m. Chng trnh ca bn c th chy khng n nh nu d liu vo ln hn kch c ca mng cha n.

V nhng nguyn nhn trn, khi mun nhp vo cc xu k t bn nn s dng cin.getline thay v cin >>.

Chuyn i xu k t sang cc kiu khc.


V mt xu k t c th biu din nhiu kiu d liu khc nh dng s nn vic chuyn i ni dung nh vy sang dng s l rt hu ch. V d, mt xu c th mang gi tr "1977"nhng l mt chui gm 5 k t (k c k t null) v khng d g chuyn thnh mt s nguyn. V vy th vin cstdlib (stdlib.h) cung cp 3 macro/hm hu ch sau:

atoi: chuyn xu thnh kiu int. atol: chuyn xu thnh kiu long. atof: chuyn xu thnh kiu float. 42

Tt c cc hm ny nhn mt tham s v tr v gi tr s (int, long hoc float). Cc hm ny khi kt hp vi phng thc getline ca cin l mt cch ng tin cy hn phng thc cin>> c in khi yu cu ngi s dng nhp vo mt s:
// cin and ato* functions #include <iostream.h> #include <stdlib.h> int main () { char mybuffer [100]; float price; int quantity; cout << "Enter price: "; cin.getline (mybuffer,100); price = atof (mybuffer); cout << "Enter quantity: "; cin.getline (mybuffer,100); quantity = atoi (mybuffer); cout << "Total price: price*quantity; return 0; } Enter price: Enter quantity: Total price: 57.75 2.75 21

"

<<

Cc hm thao tc trn chui


Th vin cstring (string.h) khng ch c hm strcpy m cn c nhiu hm khc thao tc trn chui. Di y l gii thiu lt qua ca cc hm thng dng nht: strcat: char* strcat (char* dest, const char* src); Gn thm chui src vo pha cui ca dest. Tr v dest. strcmp: int strcmp (const char* string1, const char* string2); So snh hai xu string1 v string2. Tr v 0 nu hai xu l bng nhau. strcpy: char* strcpy (char* dest, const char* src); Copy ni dung ca src cho dest. Tr v dest. strlen: size_t strlen (const char* string); Tr v di ca string. Ch : char* hon ton tng ng vi char[]

Bi 3.3

Con tr

Chng ta bit cc bin chnh l cc nh m chng ta c th truy xut di cc tn. Cc bin ny c lu tr ti nhng ch c th trong b nh. i vi chng trnh ca chng ta, b nh my tnh ch l mt dy gm cc nh 1 byte, mi c mt a ch xc nh. Mt s m hnh tt i vi b nh my tnh chnh l mt ph trong mt thnh ph. Trn mt ph tt c cc ngi nh u c nh s tun t vi mt ci tn duy nht nn nu chng ta ni n s 27 ph Trn Hng o th chng ta c th tm c ni m khng lm ln v ch c mt ngi nh vi s nh vy. 43

Cng vi cch t chc tng t nh vic nh s cc ngi nh, h iu hnh t chc b nh thnh nhng s n nht, tun t, nn nu chng ta ni n v tr 1776 trong b nh chng ta bit chnh xc nh v ch c mt v tr vi a ch nh vy.

Ton t ly a ch (&).
Vo thi im m chng ta khai bo mt bin th n phi c lu tr trong mt v tr c th trong b nh. Ni chung chng ta khng quyt nh ni no bin c t - tht may mn rng iu c lm t ng bi trnh bin dch v h iu hnh, nhng mt khi h iu hnh gn mt a ch cho bin th chng ta c th mun bit bin c lu tr u. iu ny c th c thc hin bng cch t trc tn bin mt du v (&), c ngha l "a ch ca". V d:
ted = &andy;

s gn cho bin ted a ch ca bin andy, v khi t trc tn bin andy du v (&) chng ta khng cn ni n ni dung ca bin m ch ni n a ch ca n trong b nh. Gi s rng bin andy c t nh c a ch 1776 v chng ta vit nh sau:
andy fred ted = &andy; = = 25; andy;

kt qu s ging nh trong s di y:

Chng ta gn cho fred ni dung ca bin andy nh chng ta lm rt ln nhiu khc trong nhng phn trc nhng vi bin ted chng ta gn a ch m h iu hnh lu gi tr ca bin andy, chng ta va gi s n l 1776. Nhng bin lu tr a ch ca mt bin khc (nh ted trong v d trc) c gi l con tr. Trong C++ con tr c rt nhiu u im v chng c s dng rt thng xuyn, Tip theo chng ta s thy cc bin kiu ny c khai bo nh th no.

Ton t tham chiu (*)


Bng cch s dng con tr chng ta c th truy xut trc tip n gi tr c lu tr trong bin c tr bi n bng cch trc tn bin con tr mt du sao (*) - y c th c dch l "gi tr c tr bi". V vy, nu chng ta vit: 44

beth = *ted;

(chng ta c th c n l: "beth bng gi tr c tr bi ted" beth s mang gi tr 25, v ted bng 1776 v gi tr tr bi 1776 l 25.

Bn phi phn bit c rng ted c gi tr 1776, nhng *ted (vi mt du sao ng trc) tr ti gi tr c lu tr trong a ch 1776, l 25. Hy ch s khc bit gia vic c hay khng c du sao tham chiu.
beth = ted; beth = *ted; // beth bng ted ( 1776 ) // beth bng gi tr c tr bi( 25 )

Ton t ly a ch (&) N c dng nh l mt tin t ca bin v c th c dch l "a ch ca", v vy &variable1 c th c c l "a ch ca variable1". Ton t tham chiu (*) N ch ra rng ci cn c tnh ton l ni dung c tr bi biu thc c coi nh l mt a ch. N c th c dch l "gi tr c tr bi".. *mypointer c c l "gi tr c tr bi mypointer". Vo lc ny, vi nhng v d vit trn
andy ted = &andy; = 25;

bn c th d dng nhn ra tt c cc biu thc sau l ng:


andy == 25 &andy == 1776 ted == 1776 *ted == 25

Khai bo bin kiu con tr


V con tr c kh nng tham chiu trc tip n gi tr m chng tr ti nn cn thit phi ch r kiu d liu no m mt bin con tr tr ti khai bo n. V vy, khai bo ca mt bin con tr s c mu sau:
type * pointer_name;

trong type l kiu d liu c tr ti, khng phi l kiu ca bn thn con tr. V d: 45

int * number; char * character; float * greatnumber;

l ba khai bo ca con tr. Mi bin u tr ti mt kiu d liu khc nhau nhng c ba u l con tr v chng u chim mt lng b nh nh nhau (kch thc ca mt bin con tr ty thuc vo h iu hnh). nhng d liu m chng tr ti khng chim lng b nh nh nhau, mt kiu int, mt kiu char v ci cn li kiu float. Ti phi nhn mnh li rng du sao (*) m chng ta t khi khai bo mt con tr ch c ngha rng: l mt con tr v hon ton khng lin quan n ton t tham chiu m chng ta xem xt trc . n gin ch l hai tc v khc nhau c biu din bi cng mt du.
// my first pointer #include <iostream.h> int main () { int value1 = 5, value2 = 15; int * mypointer; mypointer = &value1; *mypointer = 10; mypointer = &value2; *mypointer = 20; cout << "value1==" value2==" << value2; return 0; } value1==10 / value2==20

<<

value1

<<

"/

Ch rng gi tr ca value1 v value2 c thay i mt cch gin tip. u tin chng ta gn cho mypointer a ch ca value1 dng ton t ly a ch (&) v sau chng ta gn 10 cho gi tr c tr bi mypointer, l gi tr c tr bi value1 v vy chng ta sa bin value1 mt cch gin tip bn c th thy rng mt con tr c th mang mt vi gi tr trong cng mt chng trnh chng ta s lp li qu trnh vi value2 v vi cng mt con tr. y l mt v d phc tp hn mt cht:
// more pointers #include <iostream.h> int main () { int value1 = 5, value2 = 15; int *p1, *p2; p1 = &value1; // p1 value1 p2 = &value2; // p2 value2 *p1 = 10; // gi = 10 *p2 = *p1; // gi = gi tr tr bi p1 = a ch ca = a ch ca tr tr bi p1 tr tr bi p2 value1==10 / value2==20

46

p1 = p2; con tr) *p1 = 20; = 20

// p1 = p2 (php gn // gi tr tr bi p1 << value1 << "/

cout << "value1==" value2==" << value2; return 0; }

Mt dng c th gy s ch ca bn l:
int *p1, *p2;

dng ny khai bo hai con tr bng cch t du sao (*) trc mi con tr. Nguyn nhn l kiu d liu khai bo cho c dng l int v v theo th t t phi sang tri, du sao c tnh trc tn kiu.

Con tr v mng.
Trong thc t, tn ca mt mng tng ng vi a ch phn t u tin ca n, ging nh mt con tr tng ng vi a ch ca phn t u tin m n tr ti, v vy thc t chng hon ton nh nhau. V d, cho hai khai bo sau:
int numbers [20]; int * p;

lnh sau s hp l:
p = numbers;

y p v numbers l tng ng v chng c cng thuc tnh, s khc bit duy nht l chng ta c th gn mt gi tr khc cho con tr p trong khi numbers lun tr n phn t u tin trong s 20 phn t kiu int m n c nh ngha vi. V vy, khng ging nh p - l mt bin con tr bnh thng, numbers l mt con tr hng. Lnh gn sau y l khng hp l:
numbers = p;

bi v numbers l mt mng (con tr hng) v khng c gi tr no c th c gn cho cc hng. V con tr cng c mi tnh cht ca mt bin nn tt c cc biu thc c con tr trong v d di y l hon ton hp l:
// more pointers #include <iostream.h> int main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; 10, 20, 30, 40, 50,

47

p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; return 0;

Trong bi "mng" chng ta dng du ngoc vung ch ra phn t ca mng m chng ta mun tr n. Cp ngoc vung ny c coi nh l ton t offset v ngha ca chng khng i khi c dng vi bin con tr. V d, hai biu thc sau y:
a[5] = 0; *(a+5) = 0; // a [offset of 5] = 0 // pointed by (a+5) = 0 tng ng v hp l bt k a l mng hay l mt con tr.

l hon ton

Khi to con tr
Khi khai bo con tr c th chng ta s mun ch nh r rng chng s tr ti bin no,
int number; int *tommy = &number;

l tng ng vi:
int number; int *tommy; tommy = &number;

Trong mt php gn con tr chng ta phi lun lun gn a ch m n tr ti ch khng phi l gi tr m n tr ti. Bn cn phi nh rng khi khai bo mt bin con tr, du sao (*) c dng ch ra n l mt con tr, v hon ton khc vi ton t tham chiu. l hai ton t khc nhau mc d chng c vit vi cng mt du. V vy, cc cu lnh sau l khng hp l:
int number; int *tommy; *tommy = &number;

Nh i vi mng, trnh bin dch cho php chng ta khi to gi tr m con tr tr ti bng gi tr hng vo thi im khai bo bin con tr:
char * terry = "hello";

trong trng hp ny mt khi nh tnh c dnh cha "hello" v mt con tr tr ti k t u tin ca khi nh ny ( l k t h') c gn cho terry. Nu "hello" c lu ti a ch 1702, lnh khai bo trn c th c hnh dung nh th ny:

48

cn phi nhc li rng terry mang gi tr 1702 ch khng phi l 'h' hay "hello". Bin con tr terry tr ti mt xu k t v n c th c s dng nh l i vi mt mng (hy nh rng mt mng ch n thun l mt con tr hng). V d, nu chng ta mun thay k t 'o' bng mt du chm than, chng ta c th thc hin vic bng hai cch:
terry[4] *(terry+4) = '!'; = '!';

hy nh rng vit terry[4] l hon ton ging vi vit *(terry+4) mc d biu thc thng dng nht l ci u tin. Vi mt trong hai lnh trn xu do terry tr n s c gi tr nh sau:

Cc php tnh s hc vi pointer


Vic thc hin cc php tnh s hc vi con tr hi khc so vi cc kiu d liu s nguyn khc. Trc ht, ch php cng v tr l c php dng. Nhng c cng v tr u cho kt qu ph thuc vo kch thc ca kiu d liu m bin con tr tr ti. Chng ta thy c nhiu kiu d liu khc nhau tn ti v chng c th chim ch nhiu hn hoc t hn cc kiu d liu khc. V d, trong cc kiu s nguyn, char chim 1 byte, short chim 2 byte v long chim 4 byte. Gi s chng ta c 3 con tr sau:
char *mychar; short *myshort; long *mylong;

v chng ln lt tr ti nh 1000, 2000 and 3000. Nu chng ta vit


mychar++; myshort++; mylong++;

49

- nh bn mong i - s mang gi tr 1001. Tuy nhin myshort s mang gi tr 2002 v mylong mang gi tr 3004. Nguyn nhn l khi cng thm 1 vo mt con tr th n s tr ti phn t tip theo c cng kiu m n c nh ngha, v vy kch thc tnh bng byte ca kiu d liu n tr ti s c cng thm vo bin con tr.
mychar

iu ny ng vi c hai php ton cng v tr i vi con tr. Chng ta cng hon ton thu c kt qu nh trn nu vit:
mychar = mychar + 1; myshort = myshort + 1; mylong = mylong + 1;

Cn phi cnh bo bn rng c hai ton t tng (++) v gim (--) u c quyn u tin ln hn ton t tham chiu (*), v vy biu thc sau y c th dn ti kt qu sai:
*p++; *p++ = *q++;

Lnh u tin tng ng vi *(p++) iu m n thc hin l tng p (a ch nh m n tr ti ch khng phi l gi tr tr ti). Lnh th hai, c hai ton t tng (++) u c thc hin sau khi gi tr ca *q c gn cho *p v sau c q v p u tng ln 1. Lnh ny tng ng vi:
*p p++; q++; = *q;

Nh ni trong cc bi trc, ti khuyn cc bn nn dng cc cp ngoc n trnh nhng kt qu khng mong mun.

Con tr tr ti con tr
C++ cho php s dng cc con tr tr ti cc con tr khc ging nh l tr ti d liu. lm vic chng ta ch cn thm mt du sao (*) cho mi mc tham chiu. 50

char a; char * b; char ** c; a = 'z'; b = &a; c = &b;

gi s rng a,b,c c lu cc nh 7230, 8092 and 10502, ta c th m t on m trn nh sau:

im mi trong v d ny l bin c, chng ta c th ni v n theo 3 cch khc nhau, mi cch s tng ng vi mt gi tr khc nhau:
c l mt bin c kiu (char **) *c l mt bin c kiu (char*) **c l mt bin c kiu (char) mang gi tr 'z' mang mang gi gi tr tr 8092 7230

Con tr khng kiu


Con tr khng kiu l mt loi con tr c bit. N c th tr ti bt k loi d liu no, t gi tr nguyn hoc thc cho ti mt xu k t. Hn ch duy nht ca n l d liu c tr ti khng th c tham chiu ti mt cch trc tip (chng ta khng th dng ton t tham chiu * vi chng) v di ca n l khng xc nh v v vy chng ta phi dng n ton t chuyn kiu d liu hay php gn chuyn con tr khng kiu thnh mt con tr tr ti mt loi d liu c th. Mt trong nhng tin ch ca n l cho php truyn tham s cho hm m khng cn ch r kiu
// integer increaser #include <iostream.h> void increase (void* data, int type) { switch (type) { case sizeof(char) : (*((char*)data))+ +; break; case sizeof(short): (*((short*)data))+ +; break; case sizeof(long) : (*((long*)data))+ +; break; } } int main () { char a = 5; short b = 9; long c = 12; increase (&a,sizeof(a)); 6, 10, 13

51

increase (&b,sizeof(b)); increase (&c,sizeof(c)); cout << (int) a << ", " << b << ", " << c; } return 0;

l mt ton t ca ngn ng C++, n tr v mt gi tr hng l kch thc tnh bng byte ca tham s truyn cho n, v d sizeof(char) bng 1 v kch thc ca char l 1 byte.
sizeof

Con tr hm
C++ cho php thao tc vi cc con tr hm. Tin ch tuyt vi ny cho php truyn mt hm nh l mt tham s n mt hm khc. c th khai bo mt con tr tr ti mt hm chng ta phi khai bo n nh l khai bo mu ca mt hm nhng phi bao trong mt cp ngoc n () tn ca hm v chn du sao (*) ng trc.
// pointer to functions #include <iostream.h> int addition (int a, int b) { return (a+b); } int subtraction (int a, int b) { return (a-b); } int (*minus)(int,int) = subtraction; int operation (int x, (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return (g); } int y, int 8

int main () { int m,n; m = operation (7, 5, &addition); n = operation (20, m, minus); cout <<n; return 0; }

Trong v d ny, minus l mt con tr ton cc tr ti mt hm c hai tham s kiu int, con tr ny c gm tr ti hm subtraction, tt c u trn mt dng:
int (* minus)(int,int) = subtraction;

Bi 3.4

B nh ng

Cho n nay, trong cc chng trnh ca chng ta, tt c nhng phn b nh chng ta c th s dng l cc bin cc mng v cc i tng khc m chng ta khai bo. Kch c ca chng l c nh v khng th thay i trong thi gian chng trnh chy. Nhng nu chng ta cn mt lng b nh m kch c ca n 52

ch c th c xc nh khi chng trnh chy, v d nh trong trng hp chng ta nhn thng tin t ngi dng xc nh lng b nh cn thit. Gii php y chnh l b nh ng, C++ tch hp hai ton t new v delete thc hin vic ny Hai ton t new v delete ch c trong C++. phn sau ca bi chng ta s bit nhng thao tc tng ng vi cc ton t ny trong C. Ton t new v new[ ] c th c c b nh ng chng ta c th dng ton t new. Theo sau ton t ny l tn kiu d liu v c th l s phn t cn thit c t trong cp ngoc vung. N tr v mt con tr tr ti u ca khi nh va c cp pht. Dng thc ca ton t ny nh sau:
pointer = new type

hoc
pointer = new type [elements]

Biu thc u tien c dng cp pht b nh cha mt phn t c kiu type. Lnh th hai c dng cp pht mt khi nh (mt mng) gm cc phn t kiu type. V d:
int * bobby; bobby = new int [5];

trong trng hp ny, h iu hnh dnh ch cho 5 phn t kiu int trong b nh v tr v mt con tr tr n u ca khi nh. V vy lc ny bobby tr n mt khi nh hp l gm 5 phn t int.

Bn c th hi ti l c g khc nhau gia vic khai bo mt mng vi vic cp pht b nh cho mt con tr nh chng ta va lm. iu quan trng nht l kch thc ca mt mng phi l mt hng, iu ny gii hn kch thc ca mng n kch thc m chng ta chn khi thit k chng trnh trong khi cp pht b nh ng cho php cp pht b nh trong qu trnh chy vi kch thc bt k. B nh ng ni chung c qun l bi h iu hnh v trong cc mi trng a nhim c th chy mt lc vi chng trnh c mt kh nng c th xy ra l ht b nh cp pht. Nu iu ny xy ra v h iu hnh khng th cp pht b nh nh chng ta yu cu vi ton t new, mt con tr null (zero) s c tr v. V vy cc bn nn kim tra xem con tr tr v bi ton t new c bng null hay khng:
int * bobby; bobby = new int [5]; if (bobby == NULL) {

53

// error assigning memory. Take measures. };

Ton t delete. V b nh ng ch cn thit trong mt khong thi gian nht nh, khi n khng cn dng n na th n s c gii phng c th cp pht cho cc nhu cu khc trong tng lai. thc hin vic ny ta dng ton t delete, dng thc ca n nh sau:
delete pointer;

hoc
delete [] pointer;

Biu thc u tin nn c dng gii phng b nh c cp pht cho mt phn t v lnh th hai dng gii phng mt khi nh gm nhiu phn t (mng). Trong hu ht cc trnh dch c hai biu thc l tng ng mc d chng l r rng l hai ton t khc nhau.
// rememb-o-matic #include <iostream.h> #include <stdlib.h> int main () { char input [100]; int i,n; long * l, total = 0; cout << "How many numbers do you want to type in? "; cin.getline (input,100); i=atoi (input); l= new long[i]; if (l == NULL) exit (1); for (n=0; n<i; n++) { cout << "Enter number: "; cin.getline (input,100); l[n]=atol (input); } cout << "You have entered: "; for (n=0; n<i; n++) cout << l[n] << ", "; delete[] l; return 0; } NULL How many numbers do you want to type in? 5 Enter number : 75 Enter number : 436 Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32,

l mt hng s c nh ngha trong th vin C++ dng biu th con tr null. Trong trng hp hng s ny cha nh ngha bn c th t nh ngha n:
#define NULL 0

Dng 0 hay NULL khi kim tra con tr l nh nhau nhng vic dng NULL vi con tr c s dng rt rng ri v iu ny c khuyn khch gip cho chng trnh d c hn.

B nh ng trong ANSI-C
54

Ton t new v delete l c quyn C++ v chng khng c trong ngn ng C. Trong ngn ng C, c th s dng b nh ng chng ta phi s dng th vin stdlib.h. Chng ta s xem xt cch ny v n cng hp l trong C++ v n vn cn c s dng trong mt s chng trnh. Hm malloc y l mt hm tng qut cp pht b nh ng cho con tr. Cu trc ca n nh sau:
void * malloc (size_t nbytes);

trong nbytes l s byte chng ta mun gn cho con tr. Hm ny tr v mt con tr kiu void*, v vy chng ta phi chuyn i kiu sang kiu ca con tr ch, v d:
char * ronny; ronny = (char *) malloc (10);

on m ny cp pht cho con tr ronny mt khi nh 10 byte. Khi chng ta mun cp pht mt khi d liu c kiu khc char (ln hn 1 byte) chng ta phi nhn s phn t mong mun vi kch thc ca chng. Tht may mn l chng ta c ton t sizeof, ton t ny tr v kch thc ca mt kiu d liu c th.
int * bobby; bobby = (int *) malloc (5 * sizeof(int));

on m ny cp pht cho bobby mt khi nh gm 5 s nguyn kiu int, kch c ca kiu d liu ny c th bng 2, 4 hay hn ty thuc vo h thng m chng trnh c dch. Hm calloc. calloc hot ng rt ging vi malloc, s khc nhau ch yu l khai bo mu ca n:
void * calloc (size_t nelements, size_t size);

n s dng hai tham s thay v mt. Hai tham s ny c nhn vi nhau c c kch thc tng cng ca khi nh cn cp pht. Thng thng tham s u tin (nelements) l s phn t v tham s thc hai (size) l kch thc ca mi phn t. V d, chng ta c th nh ngha bobby vi calloc nh sau:
int * bobby; bobby = (int *) calloc (5, sizeof(int));

Mt im khc nhau na gia malloc v calloc l calloc khi to tt c cc phn t ca n v 0. Hm realloc. N thay i kch thc ca khi nh c cp pht cho mt con tr.
void * realloc (void * pointer, size_t size);

tham s pointer nhn vo mt con tr c cp pht b nh hay mt con tr null, v size ch nh kch thc ca khi nh mi. Hm ny s cp pht size byte b nh cho con tr. N c th phi thay i v v tr ca khi nh c th ch cho kch thc mi ca khi nh, trong trng hp ny ni dung hin thi ca khi nh c copy ti v tr mi m bo d liu khng b mt. Con tr mi tr ti khi nh c hm tr v. Nu khng th thay i kch thc ca khi nh th hm s tr v mt con tr null nhng tham s pointer v ni dung ca n s khng b thay i. 55

Hm free. Hm ny gii phng mt khi nh ng c cp pht bi malloc, calloc hoc realloc.


void free (void * pointer);

Hm ny ch c dng gii phng b nh c cp pht bi cc hm malloc, calloc and realloc.

Bi 3.5

Cc cu trc

Cc cu trc d liu.
Mt cu trc d liu l mt tp hp ca nhng kiu d liu khc nhau c gp li vi mt ci tn duy nht. Dng thc ca n nh sau:
struct model_name { type1 element1; type2 element2; type3 element3; . . } object_name; trong model_name l tn ca mu

kiu d liu v tham s ty chn object_name mt tn hp l cho i tng. Bn trong cp ngoc nhn l tn cc phn t ca cu trc v kiu ca chng. Nu nh ngha ca cu trc bao gm tham s model_name (tu chn), tham s ny tr thnh mt tn kiu hp l tng ng vi cu trc. V d:
struct products { char name [30]; float price; } ; products apple; products orange, melon; ta nh ngha cu trc products

Chng vi hai trng: name v price, mi trng c mt kiu khc nhau. Chng ta cng s dng tn ca kiu cu trc (products) khai bo ba i tng c kiu : apple, orange v melon. Sau khi c khai bo, products tr thnh mt tn kiu hp l ging cc kiu c bn nh int, char hay short. Trng tu chn object_name c th nm cui ca phn khai bo cu trc dng khai bo trc tip i tng c kiu cu trc. V d, khai bo cc i tng apple, orange v melon nh lm phn trc chng ta cng c th lm theo cch sau:
struct products { char name [30]; float price; } apple, orange, melon;

Hn na, trong trng hp ny tham s model_name tr thnh tu chn. Mc d nu model_name khng c s dng th chng ta s khng th khai bo thm cc i tng c kiu mu ny. 56

Mt iu quan trng l cn phn bit r rng u l kiu mu cu trc, u l i tng cu trc. Nu dng cc thut ng chng ta s dng vi cc bin, kiu mu l tn kiu d liu cn i tng l cc bin. Sau khi khai bo ba i tng c kiu l mt mu cu trc xc nh ( apple, orange and melon) chng ta c th thao tc vi cc trng to nn chng. lm vic ny chng ta s dng mt du chm ( .) chn gia tn i tng v tn trng. V d, chng ta c th thao tc vi bt k phn t no ca cu trc nh l i vi cc bin chun :
apple.name apple.price orange.name orange.price melon.name melon.price

mi trng c kiu d liu tng ng: apple.name, orange.name v melon.name c kiu char[30], v apple.price, orange.price v melon.price c kiu float. Chng ta tm bit apples, oranges v melons n vi mt v d v cc b phim:
// example about structures #include <iostream.h> #include <string.h> #include <stdlib.h> struct movies_t { char title [50]; int year; } mine, yours; void printmovie (movies_t movie); int main () { char buffer [50]; strcpy (mine.title, Odyssey"); mine.year = 1968; "2001 A Space Enter Enter title: year: movie Odyssey Alien 1979 is: (1968) yours:

My favourite 2001 A Space And Alien (1979)

cout << "Enter title: "; cin.getline (yours.title,50); cout << "Enter year: "; cin.getline (buffer,50); yours.year = atoi (buffer); cout << "My favourite movie is:\n "; printmovie (mine); cout << "And yours:\n "; printmovie (yours); return 0; } void printmovie (movies_t movie) { cout << movie.title;

57

cout << " (" << movie.year << ")\n"; }

V d ny cho chng ta thy cch s dng cc phn t ca mt cu trc v bn thn cu trc nh l cc bin thng thng. V d, yours.year l mt bin hp l c kiu int cng nh mine.title l mt mng hp l vi 50 phn t kiu chars. Ch rng c mine and yours u c coi l cc bin hp l kiu movie_t khi c truyn cho hm printmovie().Hn na mt li th quan trng ca cu trc l chng ta c th xt cc phn t ca chng mt cch ring bit hoc ton b cu trc nh l mt khi. Cc cu trc c s dng rt nhiu xy dng c s d liu c bit nu chng ta xt n kh nng xy dng cc mng ca chng.
// array of structures #include <iostream.h> #include <stdlib.h> #define N_MOVIES 5 struct movies_t { char title [50]; int year; } films [N_MOVIES]; void printmovie (movies_t movie); int main () { char buffer [50]; int n; for (n=0; n<N_MOVIES; n++) { cout << "Enter title: "; cin.getline (films[n].title,50); cout << "Enter year: "; cin.getline (buffer,50); films[n].year = atoi (buffer); } cout << "\nYou have entered movies:\n"; for (n=0; n<N_MOVIES; n++) printmovie (films[n]); return 0; } Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter title: year: title: Blade year: title: year: title: Rear year: title: Taxi year: these Alien 1979 Runner 1982 Matrix 1999 Window 1954 Driver 1975 movies: (1979) (1982) (1999) (1954)

You have entered Alien Blade Runner Matrix Rear Window Taxi Driver (1975)

these

void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")\n"; }

Con tr tr n cu trc
58

Nh bt k cc kiu d liu no khc, cc cu trc c th c tr n bi con tr. Quy tc hon ton ging nh i vi bt k kiu d liu c bn no:
struct movies_t { char title [50]; int year; }; movies_t amovie; movies_t * pmovie; amovie l mt i tng

y c kiu movies_t v pmovie l mt con tr tr ti i tng movies_t. OK, by gi chng ta s n vi mt v d khc, n s gii thiu mt ton t mi:
// pointers to structures #include <iostream.h> #include <stdlib.h> struct movies_t { char title [50]; int year; }; int main () { char buffer[50]; movies_t amovie; movies_t * pmovie; pmovie = & amovie; cout << "Enter title: "; cin.getline (pmovie->title,50); cout << "Enter year: "; cin.getline (buffer,50); pmovie->year = atoi (buffer); cout << "\nYou have entered:\n"; cout << pmovie->title; cout << " (" << pmovie->year << ")\n"; } return 0; Enter Enter You Matrix (1999) title: year: have Matrix 1999 entered:

on m trn gii thiu mt iu quan trng: ton t ->. y l mt ton t tham chiu ch dng tr ti cc cu trc v cc lp (class). N cho php chng ta khng phi dng ngoc mi khi tham chiu n mt phn t ca cu trc. Trong v d ny chng ta s dng:
movies->title

n c th c dch thnh:
(*movies).title

c hai biu thc movies->title v (*movies).title u hp l v chng u dng tham chiu n phn t title ca cu trc c tr bi movies. Bn cn phn bit r rng vi: 59

*movies.title

n tng ng vi
*(movies.title)

lnh ny dng tnh ton gi tr c tr bi phn t title ca cu trc movies, trong trng hp ny (title khng phi l mt con tr) n chng c ngha g nhiu. Bn di y tng kt tt c cc kt hp c th c gia con tr v cu trc: Biu thc M t Tng ng vi
movies.title movies->title *movies.title

Phn t title ca cu trc movies Phn t title ca cu trc c tr bi movies


(*movies).title

Gi tr c tr bi phn t title ca cu trc movies *(movies.title)

Cc cu trc lng nhau


Cc cu trc c th c t lng nhau v vy mt phn t hp l ca mt cu trc c th l mt cu trc khc.
struct movies_t { char title [50]; int year; } struct friends_t { char name [50]; char email [50]; movies_t favourite_movie; } charlie, maria; friends_t * pfriends = &charlie;

V vy, sau phn khai bo trn chng ta c th s dng cc biu thc sau:
charlie.name maria.favourite_movie.title charlie.favourite_movie.year pfriends->favourite_movie.year

(trong hai biu thc cui cng l tng ng). Cc khi nim c bn v cu trc c cp n trong phn ny l hon ton ging vi ngn ng C, tuy nhin trong C++, cu trc c m rng thm cc chc nng ca mt lp vi tnh cht c trng l tt c cc phn t ca n u l cng cng (public).

Bi 3.6

Cc kiu d liu t nh ngha.


60

Trong bi trc chng ta xem xt mt loi d liu c nh ngha bi ngi dng (ngi lp trnh): cu trc. Nhng c cn nhiu kiu d liu t nh ngha khc:

T nh ngha cc kiu d liu (typedef).


C++ cho php chng ta nh ngha cc kiu d liu ca ring mnh da trn cc kiu d liu c. c th lm vic chng ta s s dng t kho typedef, dng thc nh sau:
typedef existing_type new_type_name ;

trong existing_type l mt kiu d liu c bn hay bt k mt kiu d liu nh ngha v new_type_name l tn ca kiu d liu mi. V d
typedef typedef unsigned typedef char typedef char field [50]; char * int C; WORD; string_t;

Trong trng hp ny chng ta nh ngha bn kiu d liu mi: C, WORD, string_t v field kiu char, unsigned int, char* kiu char[50], chng ta hon ton c th s dng chng nh l cc kiu d liu hp l:
C WORD string_t field name; typedef achar, anotherchar, *ptchar1; myword; ptchar2;

c th hu dng khi bn mun nh ngha mt kiu d liu c dng lp i lp li trong chng trnh hoc kiu d liu bn mun dng c tn qu di v bn mun n c tn ngn hn.

Union
Union cho php mt phn b nh c th c truy xut di dng nhiu kiu d liu khc nhau mc d tt c chng u nm cng mt v tr trong b nh. Phn khai bo v s dng n tng t vi cu trc nhng chc nng th khc hon ton:
union model_name { type1 element1; type2 element2; type3 element3; . . } object_name;

Tt c cc phn t ca union u chim cng mt ch trong b nh. Kch thc ca n l kch thc ca phn t ln nht. V d:
union mytypes_t { char c; int i; float f; } mytypes;

nh ngha ba phn t 61

mytypes.c mytypes.i mytypes.f

mi phn t c mt kiu d liu khc nhau. Nhng v tt c chng u nm cng mt ch trong b nh nn bt k s thay i no i vi mt phn t s nh hng ti tt c cc thnh phn cn li. Mt trong nhng cng dng ca union l dng kt hp mt kiu d liu c bn vi mt mng hay cc cu trc gm cc phn t nh hn. V d:
union mix_t{ long l; struct { short hi; short lo; } s; char c[4]; } mix;

nh ngha ba phn t cho php chng ta truy xut n cng mt nhm 4 byte: mix.l, mix.s v mix.c m chng ta c th s dng tu theo vic chng ta mun truy xut n nhm 4 byte ny nh th no. Ti dng nhiu kiu d liu khc nhau, mng v cu trc trong union bn c th thy cc cch khc nhau m chng

ta c th truy xut d liu.

Cc unions v danh
Trong C++ chng ta c th s dng cc unions v danh. Nu chng ta t mt union trong mt cu trc m khng tn (phn i sau cp ngoc nhn { }) union s tr thnh v danh v chng ta c th truy xut trc tip n cc phn t ca n m khng cn n tn ca union (c cn cng khng c). V d, hy xem xt s khc bit gia hai phn khai bo sau y: union union v danh
struct { char title[50]; char author[50]; union { float dollars; int yens; } price; } book; struct { char title[50]; char author[50]; union { float dollars; int yens; }; } book;

S khc bit duy nht gia hai on m ny l trong on m u tin chng ta t tn cho union ( price) cn trong ci th hai th khng. Khi truy nhp vo cc phn t dollars v yens, trong trng hp th nht chng ta vit:
book.price.dollars book.price.yens

62

cn trong trng hp th hai:


book.dollars book.yens

Mt ln na ti nhc li rng v n l mt union, hai trng dollars v yens u chim cng mt ch trong b nh nn chng khng th gi hai gi tr khc nhau.

Kiu lit k (enum)


Kiu d liu lit k dng to ra cc kiu d liu cha mt ci g hi c bit mt cht, khng phi kiu s hay kiu k t hoc cc hng true v false. Dng thc ca n nh sau:
enum model_name { value1, value2, value3, . . } object_name;

V d, chng ta c th to ra mt kiu d liu mi c tn color lu tr cc mu vi phn khai bo nh sau:


enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

Ch rng chng ta khng s dng bt k mt kiu d liu c bn no trong phn khai bo. Chng ta to ra mt kiu d liu mi m khng da trn bt k kiu d liu no c sn: kiu color_t, nhng gi tr c th ca kiu color_t c vit trong cp ngoc nhn {}. V d, sau khi khai bo kiu lit k, biu thc sau s l hp l:
colors_t mycolor = if (mycolor == green) mycolor = red; mycolor; blue;

Trn thc t kiu d liu lit k c dch l mt s nguyn v cc gi tr ca n l cc hng s nguyn c ch nh. Nu iu ny khng oc ch nh, gi tr nguyn tng ng vi phn t u tin l 0 v cc gi tr tip theo c th tng ln 1, V vy, trong kiu d liu colors_t m chng ta nh ngha trn, white tng ng vi 0, blue tng ng vi 1, green tng ng vi 2 v c tip tc nh th. Nu chng ta ch nh mt gi tr nguyn cho mt gi tr no ca kiu d liu lit k (trong v d ny l phn t u tin) cc gi tr tip theo s l cc gi tr nguyn tip theo, v d:
enum months_t { january=1, february, march, april, may, june, july, august, september, october, november, december} y2k; trong trng hp ny, bin y2k c kiu d liu lit k months_t c th cha mt trong 12 gi tr t january n december v tng ng vi cc gi tr nguyn t 1 n 12, khng phi 0 n 11 v chng ta t january bng 1.

Bi 4.1

Cc lp
63

Lp l mt phng thc logic t chc d liu v cc hm trong cng mt cu trc. Chng c khai bo s dng t kho class, t ny c chc nng tng t vi t kho ca C struct nhng c kh nng gp thm cc hm thnh vin. Dng thc ca n nh sau:

class class_name { permission_label_1: member1; permission_label_2: member2; ... } object_name; trong class_name l tn ca lp ( kiu ngi dng t nh ngha) v trng mc nh object_name l mt
hay mt vi tn i tng hp l. Phn thn ca khai bo cha cc thnh vin ca lp, c th l d liu hay cc hm v c th l cc nhn cho php ( permission labels) l mt trong nhng t kho sau y: private:, public: hoc protected:.

Cc thnh vin private ca mt lp ch c th c truy xut t cc thnh vin khc ca lp hoc t cc lp "bn b". Cc thnh vin protected c th c truy xut t cc thnh vin trong cng mt lp v cc lp bn b, thm vo l t cc thnh vin ca cc lp tha k Cui cng, cc thnh vin public c th c truy xut t bt k ch no m lp nhn thy.

Nu chng ta khai bo cc thnh vin ca mt lp trc khi thm vo cc nhn cho php th cc thnh vin c coi l private. V d:

class CRectangle { int x, y; public: void set_values (int,int); int area (void); } rect; Khai bo lp CRectangle v mt i tng c tn rect c kiu l lp CRectangle. Lp ny cha bn thnh vin: hai vin c kiu int (x v y) trong phn private (v private l s cho php mc nh) v hai hm trong phn public: set_values() v area(), y chng ta ch mi khai bo mu.
Hy ch s khc bit gia tn lp v tn i i tng: Trong v d trc, CRectangle l tn lp cn rect l tn mt i tng c kiu CRectangle. Trong cc phn tip theo ca chng trnh chng ta c th truy xut n cc thnh vin public ca i tng rect nh l i vi cc hm hay cc bin thng thng bng cch t tn ca i tng ri sau l mt du chm v tn thnh vin ca lp (nh chng ta lm vi cc cu trc ca C). V d:

rect.set_value myarea = rect.area();

(3,4);

nhng chng ta khng c kh nng truy xut n x hay y v chng l cc thnh vin private ca lp v chng ch c th c truy xut t cc thnh vin ca cng mt lp. Bi ri? y l v d y v lp CRectangle:

// classes example #include <iostream.h> class CRectangle { int x, y;

area: 12

64

public: void set_values (int,int); int area (void) {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); }
Mt iu mi trong on m ny l ton t phm vi :: c dng trong khai bo set_values(). N c s dng khai bo bn ngoi cc thnh vin ca mt lp. Ch rng chng ta nh ngha y hm area() ngay bn trong lp trong khi hm set_values() mi ch c khai bo mu cn nh ngha ca n nm ngoi lp. Trong phn khai bo ngoi ny chng ta bt buc phi dng ton t ::. S khc bit duy nht gia vic khai bo y mt hm bn trong lp v vic ch khai bo mu l trong trng hp th nht hm s c t ng coi l inline bi trnh dch, cn trong trng hp th hai n s l mt hm thnh vin bnh thng. L do khin chng ta khai bo x v y l cc thnh vin private v chng ta nh ngha mt hm thtc vi chng (set_values()) v khng c l do g truy nhp trc tip n cc bin ny. C l trong v d rt n gin ny bn khng thy c mt tin ch ln khi bo v hai bin ny nhng trong cc d n ln hn n c th l rt quan trng khi m bo c rng cc gi tr khng b thay i mt cch khng mong mun. Mt ch li na ca lp l chng ta c th khai bo mt vi i tng khc nhau t n. V d, tip sau y l v d trc v lp CRectangle, ti ch thm phn khai bo thm i tng rectb.

// class example #include <iostream.h> class CRectangle { int x, y; public: void set_values (int,int); int area (void) {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area()

rect rectb area: 30

area:

12

65

<< endl; }
Ch rng li gi n rect.area() khng cho cng kt qu vi rectb.area() v mi i tng ca lp CRectangle c cc bin v cc hm ca ring n Trn y l nhng khi nim c bn v i tng v lp trnh hng i tng. Trong i tng cc d liu v cc hm l cc thuc tnh thay v trc y i tng l cc tham s ca hm trong lp trnh cu trc. Trong bi ny cc phn tip sau chng ta s ni n nhng li ch ca phng thc ny.

Constructors v destructors
Ni chung cc i tng cn phi khi to cc bin hoc cp pht b nh ng trong qu trnh to ra chng c th hot ng tt v trnh c vic tr v cc gi tr khng mong mun. V d, iu g s xy ra nu chng ta gi hm area() trc khi gi hm set_values?C l kt qu s l mt gi tr khng xc nh v cc thnh vin x v y cha c gn mt gi tr c th no. trnh iu ny, mt lp cn c mt hm c bit: mt constructor, hm ny c th c khai bo bng cch t tn trng vi tn ca lp. N s c gi t ng khi mt khai bo mt i tng mi hoc cp pht mt i tng c kiu l lp . Chng ta thm mt constructor vo lp CRectangle:

// classes example #include <iostream.h> class CRectangle { int width, height; public: CRectangle (int,int); int area (void) (width*height);} };

rect rectb area: 30

area:

12

{return

CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; }
Nh bn c th thy, kt qu ca v d ny ging vi v d trc. Trong trng hp ny chng ta ch thay th hm set_values bng mt hm constructor. Hy ch cch m cc tham s c truyn cho constructor khi mt i tng c to ra:

CRectangle CRectangle rectb (5,6);

rect

(3,4);

Bn c th thy rng constructor khng c gi tr tr v, ngay c kiu void cng khng. iu ny lun lun phi nh vy.

66

Destructor lm cc chc nng ngc li. N s c t ng gi khi mt i tng c gii phng khi b nh hay phm vi tn ti ca n kt thc (v d nh nu n c nh ngha l mt i tng cc b bn trong mt hm v khi hm kt thc th phm vi tn ti ca n cng ht) hoc n l mt i tng i tng c cp pht ng v s gii phng bi ton t delete. Destructor phi c cng tn vi tn lp vi du (~) ng trc v n khng c tr v gi tr no. Destructor c bit ph hp khi m mt i tng cp pht b nh ng trong qu trnh tn ti ca n v trong thi im b hu b chng ta mun gii phng b nh m n s dng.

// example on constructors and destructors #include <iostream.h> class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area (void) {return (*width * *height);} }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }

rect rectb area: 30

area:

12

Qu ti cc Constructors
Nh bt k hm no khc, mt constructor c th c qu ti bi mt vi hm c cng tn nhng khc kiu hay khc s tham s. Nh rng mt thi im trnh dch ch thc hin mt hm ph hp (xem phn 2.3, Hm-II). Do vy ch mt hm constructor ph hp c gi vo thi im mt i tng lp c khai bo. Trong thc t, khi khai bo mt lp m chng ta khng ch nh mt hm constructor no th trnh dch s t ng to ra hai constructor qu ti ("constructor mc nh" v "copy constructor"). V d, i vi lp:

class CExample { public: int a,b,c; void multiply (int n, int m) { a=n; b=m; c=a*b; }; };

67

trnh dch s t ng cho rng lp c hai constructor sau:

Constructor y l mt constructor khng c tham s. N chng lm g c.

rng

CExample::CExample () { };
Copy constructor y l mt constructor c mt tham s cng kiu vi lp. N thc hin mt vic l gn tt c cc bin thnh vin khng tnh (nonstatic) ca lp gi tr ca bin tng ng ca i tng tham s.

CExample::CExample (const CExample& rv) { a=rv.a; b=rv.b; c=rv.c;

Cn phi nhn mnh rng cc constructor mc nh ny ch tn ti nu khng c constructor c khai bo. Tt nhin l bn c th qu ti constructor ca n cung cp cc constructor khc nhau cho cc mc ch khc nhau:

// overloading class constructors #include <iostream.h> class CRectangle { int width, height; public: CRectangle (); CRectangle (int,int); int area (void) (width*height);} }; CRectangle::CRectangle () { width = 5; height = 5; } CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb; cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; }

rect rectb area: 25

area:

12

{return

Trong trng hp ny rectb c khai bo khng dng tham s, v vy n c khi to vi constructor khng c tham s, constructor ny t width v height bng 5. Ch rng nu chng ta khai bo mt i tng mi v khng mun truyn tham s cho n th khng cn phi cp ngoc n ():

CRectangle rectb;

// ng

68

CRectangle rectb(); // sai!

Con tr ti lp
To con tr tr ti cc lp l hon ton hp l, c th lm vic ny chng ta hiu rng mt khi c khai bo, lp tr thnh mt kiu d liu hp l, v vy chng ta c dng tn lp l kiu cho con tr. V d:

CRectangle * prect;
l mt con tr tr ti mt i tng ca lp CRectangle. Tng t vi cu trc, tham chiu trc tip ti mt thnh vin ca mt i tng c tr bi mt con tr bn nn dng ton t ->. y l mt v d:

// pointer to classes example #include <iostream.h> class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return height);} };

a *b *c d[0] d[1] area: 56 (width *

area: area: area: area:

2 12 2 30

void CRectangle::set_values (int a, int b) { width = a; height = b; } int main () { CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b->set_values (3,4); d->set_values (5,6); d[1].set_values (7,8); cout << "a area: " << a.area() << endl; cout << "*b area: " << b->area() << endl; cout << "*c area: " << c->area() << endl; cout << "d[0] area: " << d[0].area() << endl; cout << "d[1] area: " << d[1].area() << endl; return 0; }
Di y l l bng tm tt v cc chc nng ca cc ton t lp (*, &, ., ->, [ ]) v cc con tr lp xut hin trong v d trn:

*x

c th c l:

tr bi x

69

&x c th c l: a ch ca x x.y c th c l: thnh vin y ca i tng x (*x).y c th c l: thn vin y ca i tng c tr bi x x->y c th c c l: thnh vin y ca i tng c tr bi x(tng ng vi dng trn) x[0] c th c l: i tng u tin c tr bi x x[1] c th c l: i tng th hai c tr bi x x[n] c th c c l: i tng th (n+1)c tr bi x

Cc lp c nh ngha bng t kho

struct

Ngn ng C++ m rng t kho struct ca C lm cho n cng c cc chc nng nh t kho class ngoi tr mt iu l cc thnh vin ca n mc nh l public thay v private. Tuy nhin, mc d c class v struct gn nh l tng ng trong C++, struct thng ch dng cc cu trc d liu cn class th dng cho cc lp c c cc th tc v hm thnh vin.

Bi 4.2
int a, b, c; a = b + c;

Qu ti cc ton t

C++ cho php s dng cc ton t chun ca ngn ng gia cc lp ging nh vi cc kiu d liu c bn. V d:

l hon ton hp l v cc bin y u c kiu l cc kiu d liu c bn. Tuy nhin, vic chng ta c th thc hin thao tc sau y c v khng hin nhin lm (thc t l n khng hp l):

struct { char product [50]; float price; } a, b, c; a = b + c;


Php gn mt lp (hay mt cu trc) vi mt i tng cng kiu l c php (copy constructor mc nh). Nhng php cng s gy ra li v n c dng vi cc kiu d liu khng c bn. Nhng cn phi cm n kh nng qu ti ton t ca C++, chng ta c th lm cho cc i tng kiu nh trn c th chp nhn cc ton t m khng lm thay i ngha ca n i vi cc kiu d liu c bn. Di y l danh sch tt c cc ton t c th c qu ti: + * / = < > <<= >>= == != <= >= ++ ~ &= ^= |= && || %= lm qu ti mt ton t chng ta ch cn vit t chng ta mun lm qu ti. Mu nh sau: += -= *= /= << >> -% & ^ ! | [] () new delete mt hm thnh vin ca lp c tn operator theo sau l ton

type operator sign (parameters);


Di y l v d v vic qu ti ton t +. Chng ta chun b tnh tng hai vector hai chiu a(3,1) v b(1,2). Php cng gia hai vector hai chiu ch n gin l cng hai to x ly to kt qu x , cng hai to y ly to kt qu y. Trong trng hp ny kt qu s l (3+1,1+2) = (4,3).

// vectors: v d v qu ti ton t #include <iostream.h> class CVector { public: int x,y;

4,3

70

CVector () {}; CVector (int,int); CVector operator + (CVector); }; CVector::CVector (int a, int b) { x = a; y = b; } CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); } int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; }
Nu bn thy qu nhiu CVector hy rng mt s trong chng tham chiu n tn lp CVector cn s cn li l tn cc hm (constructor v destructor). ng ln ln CVector (int, int); // Hm c tn Vector (constructor) CVector operator+ (CVector); // Hm operator+ tr v kiu CVector Hm operator+ ca lp CVector c dng qu ti ton t s hc +. Hm ny c th c gi bng mt trong cc cch:

c = c = a.operator+ (b);

b;

Hy ch rng chng ta thm vo constructor rng (khng c tham s) v chng ta nh ngha n vi mt khi lnh cng rng nt:

CVector () { };
iu ny l cn thit v cn c mt constructor khc,

CVector (int, int);


v v vy cc constructors mc nh khng tn ti trong CVector nu chng ta khng khai n mt cch r rng. Khai bo sau y s l khng hp l:

CVector c;
D th no chng na, ti cn phi cnh bo rng mt khi lnh rng khng nn to mt constructor v n khng tho mn chc nng ti thiu m mt constructor nn c, l vic khi to tt c cc bin trong lp. Trong trng hp ca chng ta constructor ny cc bin x v y l khng xc nh. V vy mt khai bo thch

71

hp hn s l mt ci g ging nh th ny:

CVector () { x=0; y=0; };


cho n gin ti khng vit vo trong v d trn. Cng vi vic to mt constructor rng v mt copy constructor, C++ cn mc nh nh ngha ton t gn (=) gia hai lp c cng mt kiu. N copy ton b ni dung ca cc thnh vin khng tnh (non-static) ca i tng bn phi php gn cho i tng bn tri. Tt nhin bn c th nh ngha li n thc hin chc nng khc m bn mun, v d nh ch copy mt s thnh vin no ca lp. Vic qu ti cc ton t khng bt buc hot ng ca n phi lin quan n ngha thng thng ca n mc d iu ny l nn lm. V d c v khng logic lm nu s dng ton t + tr hai lp hay ton t == in s 0 vo mt lp mc d iu l hon ton hp l. Mc d khai bo mu ca hm operator+ l kh hin nhin v n ly phn bn phi ca ton t lm tham s cho hm operator+, cc ton t khc khng phi ci no cng r rng nh th. y chng ta c mt bng tng kt v vic cc hm operator phi c khai bo nh th no (thay th @ bng cc ton t tng ng): Biu thc Ton t (@) Hm thnh vin Hm ton cc

@a a@ a@b

+ - * & ! ~ ++ A::operator@() -++ -A::operator@(int) + - * / % ^ & | < > == != <= >= A::operator@(B) << >> && || , = += -= *= /= %= ^= &= |= <<= A::operator@(B) >>= [ ] () -> A::operator()(B, C...) A::operator->()

operator@(A) operator@(A, int) operator@(A, B)

a@b a(b, c...) a->b

* trong a l mt i tng ca lp A, b l mt i tng ca lp B v c l mt i tng ca lp C. Nh bn c th thy trong bng ny, c hai cch qu ti cc ton t ca lp: nh l mt hm thnh vin v nh l mt hm ton cc. Khc nhau gia chng khng r rng tuy nhin ti cn phi nhc li rng cc hm khng phi l thnh vin ca mt lp khng th truy xut n cc thnh vin l private hoc protected ca lp tr phi hm ton cc l bn ca lp (thut ng ny s c cp n bi sau).

T kho

this

T kho this bn trong mt lp i din cho i tng ca lp ang c thc hin trong b nh. N l mt con tr lun c gi tr l a ch ca i tng. N c th c dng kim tra xem tham s c truyn cho mt hm thnh vin c phi chnh bn thn i tng hay khng. V d:

// this #include <iostream.h>

yes, &a is b

72

class CDummy { public: int isitme (CDummy& param); }; int CDummy::isitme (CDummy& param) { if (&param == this) return 1; else return 0; } int main () { CDummy a; CDummy* b = &a; if ( b->isitme(a) ) cout << "yes, &a is b"; return 0; }
N cng thng c dng trong hm thnh vin operator= m tr v a ch i tng (trnh vic s dng i tng tm thi). Tip theo v d v vector u bi chng ta c th vit mt hm operator= nh sau:

CVector& CVector::operator= (const CVector& param) { x=param.x; y=param.y; return *this; }


Trong thc t y chnh l on m c mc nh to ra nu chng ta khng vit hm thnh vin operator=.

Cc thnh vin tnh


Mt lp c th cha cc thnh vin tnh, c d liu v cc hm. Cc d liu tnh cn c gi l "bin ca lp" v ni dung ca chng khng ph thuc vo mt i tng no. Ch c mt gi tr duy nht cho tt c cc i tng trong cng mt lp. V d, n c th c trong trng hp bn mun c mt bin cha s i tng thuc lp c khai bo:

// static members in classes #include <iostream.h> class CDummy { public: static int n; CDummy () { n++; }; ~CDummy () { n--; }; }; int CDummy::n=0; int main () { CDummy a; CDummy b[5]; CDummy * c = new CDummy; cout << a.n << endl;

7 6

73

delete c; cout << CDummy::n << endl; return 0; }


Trong thc t, cc thnh vin tnh c cng thuc tnh vi cc bin ton cc. V vy, trnh vic chng b khai bo nhiu ln, theo chun ANSI-C++ chng ta ch c vit phn khai bo mu trong phn khai bo ca lp. c th khi to mt thnh vin tnh chng ta phi vit mt nh ngha bn ngoi lp, ging nh trong v d trc. V n l mt bin duy nht cho tt c cc i tng thuc lp, n c th c tham chiu n nh l thnh vin ca bt k i tng no thuc lp hay thm ch chnh bn thn tn lp (tt nhin iu ny ch hp l vi cc thnh vin tnh): cout << a.n; cout << CDummy::n; Hai li gi trong v d trn u tham chiu n cng mt bin: bin tnh n trong lp CDummy. Mt ln na, ti phi nhc li rng n l mt bin ton cc (ngha l bn c th truy xut n t bt k u). S khc bit duy nht l bn phi dng n vi tn lp. Chng ta cng c th to ra cc hm tnh ging nh cc bin tnh. Chng cng c ngha nh i vi cc bin tnh: l cc hm ton cc c th c gi nh th l cc i tng ca mt lp. Chng ch c th truy xut n phn d liu tnh cng nh khng c php s dng t kho this v n to tham chiu n mt con tr i tng. Cc hm ny thc t khng phi l thnh vin ca bt k i tng no m thc cht l ca lp.

Bi 4.3

Quan h gia cc lp
friend

Cc hm bn b (t kho

Trong bi trc chng ta c bit rng c ba mc bo v khc nhau i vi cc thnh vin trong mt lp: public, protected v private. i vi cc thnh vin protected v private, chng khng th c truy xut bn ngoi lp m chng c khai bo. Tuy nhin ci g cng c ngoi l, bng cch s dng t kho friend trong mt lp chng ta c th cho php mt hm bn ngoi truy xut vo cc thnh vin protected v private trong mt lp. c th cho php mt hm bn ngoi truy xut vo cc thnh vin private v protected ca mt lp chng ta phi khai bo mu hm vi t kho friend bn trong phn khai bo ca lp. Trong v d sau chng ta khai bo hm bn b duplicate:

// friend functions #include <iostream.h> class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return (width * height);} friend CRectangle duplicate (CRectangle); };

24

74

void CRectangle::set_values (int a, int b) { width = a; height = b; } CRectangle duplicate (CRectangle rectparam) { CRectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres); } int main () { CRectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << rectb.area(); }
bn trong hm duplicate, chng ta c th truy xut vo cc thnh vin width v height ca cc i tng khc nhau thuc lp CRectangle. Hy ch rng duplicate() khng phi l thnh vin ca lp CRectangle. Ni chung vic s dng cc hm bn b khng nm trong phng thc lp trnh hng i tng, v vy tt hn l hy s dng cc thnh vin ca lp bt c khi no c th. Nh trong v d trc, chng ta hon ton c th tch hp duplicate() vo bn trong lp.

Cc lp bn b (friend)
Ngoi vic c th khai bo cc hm bn b, chng ta cng c th nh ngha mt lp l bn ca mt lp khc. Vic ny s cho php lp th hai c th truy xut vo cc thnh vin protected and private ca lp th nht:

// friend class #include <iostream.h> class CSquare; class CRectangle { int width, height; public: int area (void) {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle; }; void CRectangle::convert (CSquare a) {

16

75

width = a.side; height = a.side;

int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0; }
Trong v d ny chng ta khai bo CRectangle l bn ca CSquare nn CRectangle c th truy xut vo cc thnh vin protected and private ca CSquare, c th hn l CSquare::side, bin nh ngha kch thc ca hnh vung. Bn c th thy mt iu mi l trong chng trnh, l phn khai bo mu rng ca lp CSquare, iu ny l cn thit v bn trong phn khai bo ca CRectangle chng ta tham chiu n CSquare (nh l mt tham s trong convert()). Phn nh ngha y ca CSquare c vit sau. Ch rng tnh bn gia hai lp c th khng nh nhau nu chng ta khng ch nh. Trong v d ny CRectangle c coi l bn ca CSquare nhng i vi CRectangle th khng. Bi vy CRectangle c th truy xut vo cc thnh vin protected v private ca CSquare nhng iu ngc li l khng ng. Tuy nhin chng c g cm on chng ta khai bo CSquare l bn ca CRectangle.

S tha k gia cc lp
Mt trong nhng tnh nng quan trng ca lp l s tha k. N cho php chng ta to mt i tng xut php t mt i tng khc. V d, gi s chng ta mun khai bo mt lot cc lp m t cc a gic nh l CRectangle hay CTriangle. C hai u c nhng c tnh chung, v d nh l chiu cao v y. iu ny c th c biu din bng lp CPolygon m t chng ta c th tha k hai lp, l CRectangle v CTriangle.

Lp CPolygon s cha cc thnh vin chung i vi mi a gic. Trong trng hp ca chng ta: chiu rng v chiu cao. Cc lp xut pht t cc lp khc c tha hng tt c cc thnh vin nhn thy c ca lp. iu ny c ngha l mt lp c s c thnh vin A v chng ta to thm mt lp xut pht t n vi mt thnh vin mi l B, lp c tha k s c c A v B. c th tha k mt lp t mt lp khc, chng ta s dng ton t : (du hai chm ) trong phn khai bo ca lp con:

76

class derived_class_name: public base_class_name;


trong derived_class_name l tn ca lp con (lp c tha k) v base_class_name l tn ca lp c s. public c th c thay th bi protected hoc private, n xc nh quyn truy xut i vi cc thnh vin c tha k nh chng ta s thy v d ny:

// derived classes #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; }

20 10

Nh bn c th thy, cc i tng ca lp CRectangle v CTriangle cha tt c cc thnh vin ca CPolygon, l width, height v set_values(). T kho protected tng t vi private, s khc bit duy nht ch xy ra khi tha k cc lp. Khi chng ta tha k mt lp, cc thnh vin protected ca lp c s c th c dng bi cc thnh vin khc ca lp c tha k cn cc thnh vin private th khng. V chng ta mun rng width v height c th c tnh ton bi cc thnh vin ca cc lp c tha k CRectangle v CTriangle ch khng ch bi cc thnh vin ca CPolygon, chng ta s dng t kho protected thay v private. Chng ta c th tng kt li cc kiu truy xut khc nhau tu theo ai truy xut chng: Truy xut Cc thnh vin trong cng lp Khng phi l thnh vin

public protected private


c c c c khng c khng khng

Cc thnh vin ca cc lp tha k c

trong "khng phi l thnh vin" i din cho bt k s tham chiu no t bn ngoi lp, v d nh l t main(), t mt lp khc hay t bt k hm no.

77

Trong v d ca chng ta, cc thnh vin c tha k bi CRectangle v CTriangle cng tun theo cc quyn truy xut nh i vi lp c s CPolygon:

CPolygon::width CRectangle::width CPolygon::set_values() CRectangle::set_values()

// protected access // protected access // public access // public access

C iu ny v chng ta tha k mt lp t mt lp khc vi quyn truy xut public, hy nh:

class CRectangle: public CPolygon;


t kho public i din cho mc bo v ti thiu m cc thnh vin c tha k ca lp c s (CPolygon) phi c c trong lp mi (CRectangle). Mc ny i vi cc thnh vin c tha k c th c thay i nu thay v dng public chng ta s dng protected hay private, v d, gi s rng daughter l mt lp c tha k t mother, chng nh ngha nh th ny:

class daughter: protected mother;


iu ny s thit lp protected l mc truy xut ti thiu cho cc thnh vin ca daughter c tha k t lp c s. C ngha l tt c cc thnh vin public trong mother s tr thnh protected trong daughter. Tt nhin, iu ny khng cn tr daughter c th c cc thnh vin public ca ring n. Mc ti thiu ny ch p dng cho cc thnh vin c tha k t mother. Nu khng c mc truy xut no c ch nh, private c dng vi cc lp c to ra vi t kho class cn public c dng vi cc cu trc.

Nhng g c tha k t lp c s?
V nguyn tc tt c cc thnh vin ca lp u c tha k tr:

Constructor v destructor Thnh vin operator=() Bn b

Mc d constructor v destructor ca lp c s khng c tha k, constructor mc nh (constructor khng c tham s) v destructor ca lp c s lun lun c gi khi mt i tng ca lp c tha k c to lp hay ph hu. Nu lp c s khng c constructor mc nh hay bn mun mt constructor qu ti c gi khi mt i tng mi ca lp c tha k c to lp, bn c th ch nh n mi nh ngha ca constructor trong lp c tha k:

derived_class_name (parameters) : base_class_name (parameters) {}


V d:

// constructors and derivated classes #include <iostream.h>

mother: daughter:

no int

parameters parameter parameter

class mother { mother: int public: son: int parameter mother () { cout << "mother: no parameters\n"; }

78

} };

mother (int a) { cout << "mother: int parameter\n";

class daughter : public mother { public: daughter (int a) { cout << "daughter: parameter\n\n"; } }; class son : public mother { public: son (int a) : mother (a) { cout << parameter\n\n"; } }; int main () { daughter cynthia (1); son daniel(1); } return 0;

int

"son:

int

Hy quan st s khc bit gia vic constructor ca mother c gi khi khi mt i tng daughter mi c to lp v khi mt i tng son c to lp. S d c s khc bit ny l do phn khai bo constructor ca daughter v son:

daughter (int a) mc nh son (int a) : mother (a)

// khng c g c ch nh: gi constructor // constructor c ch nh: gi ci ny

a tha k
Trong C++ chng ta c th to lp mt lp tha k cc trng v cc phng thc t nhiu hn mt lp. iu ny c th thc hin bng cch tch cc lp c s khc nhau bng du phy trong phn khai bo ca lp c tha k. V d, nu chng ta c mt lp dng in ra mn hnh ( COutput) v chng ta mun cc lp ca chng ta CRectangle v CTriangle cng tha k cc thnh vin ca n cng vi cc thnh vin ca CPolygon, chng ta c th vit:

class CRectangle: public CPolygon, public COutput { class CTriangle: public CPolygon, public COutput {
y l v d y :

// a tha k #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;}

20 10

79

}; class COutput { public: void output (int i); }; void COutput::output (int i) { cout << i << endl; } class CRectangle: public CPolygon, public COutput { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon, public COutput { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0; }

Bi 4.4 Cc thnh vin o. a hnh.


c th hiu c phn ny bn cn hiu r v cch s dng con tr v tha k gia cc lp. Nu c vi biu thc no c v l lng vi bn, bn c th xem li cc phn sau:

int a::b(c) {}; // Cc lp (Bi 4.1) a->b // Con tr v i tng (Bi 4.2) class a: public b; // Quan h gia cc lp(Bi 4.3)

Con tr ti lp c s
Mt trong nhng li th ln ca vic tha k cc lp l mt con tr tr ti mt lp c tha k l tng thch v kiu vi mt con tr tr ti lp c s ca n. Bi ny s cp y n vic tn dng tnh nng mnh m ny ca C++. V d, chng ta s vit li chng trnh ca chng ta v hnh ch nht v hnh tam gic trong chng trc xem xt tnh nng ny:

// con tr ti lp c s #include <iostream.h> class CPolygon { protected:

20 10

80

int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << rect.area() << endl; cout << sqre.area() << endl; return 0; }
Hm main to hai con tr tr ti hai i tng ca lp CPolygon, l *ppoly1 v *ppoly2. Chng c gn cho a ch ca rect v trgl, y l cc i tng thuc lp tha k t CPolygon nn l nhng php gn hp l. S hn ch duy nht khi s dng *ppoly1 v *ppoly2 thay v rect v trgl l c *ppoly1 v *ppoly2 u c kiu l CPolygon* v v vy chng ta ch c th tham chiu n cc thnh vin m CRectangle v CTriangle c tha k t CPolygon. V nguyn nhn chng ta khng th gi n thnh vin area() khi dng *ppoly1 v *ppoly2. cc con tr c th truy xut n area() nh l mt thnh vin hp l, cn phi khai bo thnh vin ny trong lp c s ch khng ch trong cc lp tha k.

Cc thnh vin o
Nu mun khai bo mt phn t trong mt lp m chng ta mun nh ngha li n trong cc lp tha k th chng ta phi t trc n t kho virtual vic s dng con tr ti cc i tng thuc lp ny l thch hp. Hy xem v d sau:

// cc thnh vin o #include <iostream.h> class CPolygon { protected: int width, height; public:

20 10 0

81

};

void set_values (int a, int b) { width=a; height=b; } virtual int area (void) { return (0); }

class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon poly; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; CPolygon * ppoly3 = &poly; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly3->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; cout << ppoly3->area() << endl; return 0; }
By gi c ba lp (CPolygon, CRectangle v CTriangle) u c cng cc thnh vin: width, height, set_values() v area().

area() c nh ngha l virtual v n s c nh ngha li trong cc lp tha k. Bn c th kim tra li rng nu bn b t kho v thc hin chng trnh th kt qu s l 0 cho c 3 a gic thay v 20,10,0. Nguyn nhn l do thay v gi hm area() tng ng vi mi i tng (CRectangle::area(), CTriangle::area() v CPolygon::area()), CPolygon::area() s c gi cho tt c thng qua mt con tr ti CPolygon.

Tru tng ho lp c s
Cc lp tru trng l mt ci g rt ging vi lp lp CPolygon trong v d trc ca chng ta. S khc bit duy nht l trong v d chng ta nh ngha hm area() cho cc i tng thuc lp CPolygon (ging nh i tng poly), trong khi trong mt lp tru tng c s chng ta c th b qua vic nh ngha hm ny bng cch thm =0(bng khng) vo phn khai bo hm. Lp CPolygon c th c nh ngha nh sau:

// abstract class CPoligon class CPolygon { protected: int width, height;

82

public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; }; Hy ch cch chng ta thm =0 vo virtual int area (void) thay v nh ngha y cho hm. Kiu
hm ny c tn l l pure virtual function (hm o thun tu) v tt c cc lp cha bt k mt hm o thun tu no u c coi l lp tru tng c s. S khc bit ln ca mt lp tru tng c s l khng th to c cc i tng thuc lp. Nhng chng ta c th to cc con tr tr n chng. V vy mt khai bo nh sau:

CPolygon poly;
s l khng hp l cho lp tru tng c s c khai bo trn. Tuy nhin con tr:

CPolygon CPolygon * ppoly2

ppoly1;

l hon ton hp l. C iu ny v hm tru tng thun tu m n c khng c nh ngha v khng th to c mt i tng nu nh cha nh ngha tt c cc thnh vin ca n. Tuy nhin mt con tr tr ti mt i tng thuc lp tha k m hm ny c nh ngha l hon ton hp l. Di y chng ta c mt v d y :

// cc thnh vin o. #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl;

20 10

83

return 0; }
Nu bn xem li chng trnh bn s thy rng chng ta tham chiu n cc i tng thuc cc lp khc nhau nhng ch s dng mt kiu con tr duy nht. iu ny l cc k hu dng, by gi chng ta c th to mt hm thnh vin ca CPolygon c kh nng in ra mn hnh kt qu ca hm area() m khng ph thuc vo lp c tha k l lp no.

// ejemplo miembros virtuales #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout << this->area() << endl; } }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); return 0; }

20 10

Hy nh rng this biu din mt con tr tr n i tng ang c thc hin. Cc lp tru tng v cc thnh vin o cung cp cho C++ tnh nng a hnh khin cho vic lp trnh hng i tng tr thnh mt cng c hu dng. Tt nhin chng ta thy cch n gin nht s dng nhng tnh nng ny, nhng hy tng tng nu nhng tnh nng ny c p dng cho cc mng cc i tng hay cc i tng c cp pht thng qua b nh ng.

84

85

Bi 5.1

Templates

Cc mu hm
Cc mu cho php to cc hm c th chp nhn bt k kiu d liu no lm tham s v tr v gi tr m khng phi lm qu ti hm vi tt c cc kiu d liu c th. Khai bo mu ca n c th l mt trong hai kiu sau:

template <class indetifier> function_declaration; template <typename indetifier> function_declaration;


s khc bit duy nht gia hai kiu khai bo mu ny l vic s dng t kho class hay typename, s khc nhau gia chng l khng r rng v c hai u c cng mt ngha v u cho mt kt qu nh nhau. V d, to mt hm mu tr v gi tr ln hn ca hai i tng chng ta c th s dng:

dng u tin, chng ta to mt mu cho mt kiu d liu tng qut vi tn GenericType. V vy trong hm sau , GenericType tr thnh mt kiu d liu hp l v n c s dng nh l mt kiu d liu cho hai tham s a, b v gi tr tr v ca hm GetMax.

template <class GenericType> GenericType GetMax (GenericType a, GenericType b) { return (a>b?a:b); }

GenericType thc s khng biu din mt kiu d liu c th no, chng ta c th gi hm vi bt k kiu d liu hp l no. Kiu d liu ny s p ng nh l pattern(mu) v s thay th GenericType bn trong hm.
Cch thc gi mt lp mu vi mt kiu d liu mu nh sau:

function <pattern> (parameters);


V d, gi hm GetMax v so snh hai gi tr nguyn kiu int chng ta c th vit:

int x,y; GetMax <int> (x,y);


Ok, di y l v d y :

// mu hm #include <iostream.h> template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n;

6 10

86

k=GetMax<int>(i,j); n=GetMax<long>(l,m); cout << k << endl; cout << n << endl; return 0; }
(Trong trng hp ny chng ta gi kiu d liu tng qut l T thay v GenericType v n ngn hn, thm vo n l mt trong nhng tn ph bin nht c dng cho mu mc d chng ta c th s dng bt c tn hp l no). v d trn chng ta s dng cng mt hm GetMax() vi cc tham s kiu int v long ch vi mt phin bn duy nht ca hm. Nh vy c th ni chng ta vit mt mu hm v gi n bng hai kiu khc nhau. Nh bn c th thy, bn trong mu hm GetMax() kiu T c th c dng khai bo cc i tng mi:

T result;
Trong trng hp c th ny kiu d liu tng qut T c s dng nh l tham s chao hm GetMax, trnh bin dch c th t ng tm thy kiu d liu no phi truyn cho n m khng cn bn phi ch nh <int> hay <long>. Bi vy chng ta c th vit:

int GetMax (i,j);


Cch ny c s dng ph bin hn v cng cho kt qu nh vy:

i,j;

// mu hm II #include <iostream.h> template <class T> T GetMax (T a, T b) { return (a>b?a:b); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout << z << endl; cout << n << endl; return 0; }

6 10

Ch trong trng hp ny, bn trong hm main() chng ta gi hm mu GetMax() m khng ch nh r kiu d liu gia hai ngoc nhn <>. Trnh bin dch s t ng xc nh kiu d liu no l cn thit ch mi li gi. V hm mu ca chng ta ch dng mt kiu d liu ( class T) v c hai tham s ca n u c cng mt kiu, chng ta khng th gi hm mu vi tham s l hai i tng c kiu khc nhau:

int i; long l; k = GetMax (i,l);


Chng ta cng c th khin cho hm cho hm mu chp nhn nhiu hn mt kiu d liu tng qut. V d:

87

template <class T, class U> T GetMin (T a, U b) { return (a<b?a:b); } Trong trng hp ny, hm mu GetMin() chp nhn hai tham s c kiu khc nhau v tr v mt i tng c cng kiu vi tham s u tin (T). V d, sau khi khai bo nh trn chng ta c th gi hm nh sau: int i,j; long l; i = GetMin<int,long> (j,l);
hoc thm ch:

i = GetMin (j,l);

Cc lp mu
Chng ta cng c th vit cc lp mu, mt lp m c cc thnh vin da trn cc kiu d liu tng qut khng cn phi c nh ngha thi im to lp. V d

template <class T> class pair { T values [2]; public: pair (T first, T second) { values[0]=first; values[1]=second; } };
Lp m chng ta va nh ngha dng lu tr hai phn t c kiu bt k. V d, nu chng ta mun khai bo mt i tng thuc lp ny lu tr hai gi tr nguyn kiu int c gi tr l 115 and 36 chng ta c th vit:

pair<int> myobject (115, 36);


lp ny cng c th c dng lu tr bt k kiu d liu no khc:

pair<float> myfloats (3.0, 2.18);


Hm thnh vin duy nht c nh ngha inline bn trong nh ngha ca lp, tuy nhin nu chng ta nh ngha mt hm thnh vin bn ngoi lp chng ta lun phi t trc dng nh ngha tin t template <... >.

// mu lp #include <iostream.h> template <class T> class pair { T value1, value2; public: pair (T first, T second) {value1=first; value2=second;} T getmax (); }; template <class T> T pair<T>::getmax () { T retval; retval = value1>value2? value1 : value2; return retval; }

100

88

int main () { pair <int> myobject (100, 75); cout << myobject.getmax(); return 0; }
ch cch bt u nh ngha hm getmax :

template <class T> T pair<T>::getmax ()


Tt c cc T xut hin u l cn thit. Mi khi bn khai bo mt hm thnh vin bn s phi theo mt khun mu tng t nh th.

Chuyn mn ho mu
Vic chuyn mn ho mu cho php mt mu to ra nhng bn thc thi c bit khi lm vic vi mt loi d liu xc nh no . V d, gi s rng lp mu pair c mt hm dng tr v phn d trong php chia gia hai trng trong, nhng chng ta ch mun n lm vic khi kiu d liu l int cn nhng kiu cn li th hm lun tr v 0. N c th c lm theo cch sau:

// Chuyn mn ho mu #include <iostream.h> template <class T> class pair { T value1, value2; public: pair (T first, T second) {value1=first; value2=second;} T module () {return 0;} }; template <> class pair <int> { int value1, value2; public: pair (int first, int second) {value1=first; value2=second;} int module (); }; template <> int pair<int>::module() { return value1%value2; } int main () { pair <int> myints (100,75); pair <float> myfloats (100.0,75.0); cout << myints.module() << '\n'; cout << myfloats.module() << '\n'; return 0; }

25 0

Nh bn c th thy s chuyn mn ho c nh ngha theo cch sau:

template <> class class_name <type>

89

S chuyn mn ho ny l mt phn ca mt mu, v vy chng ta phi bt u phn khai bo vi template <>. V r rng rng l s chuyn mn ho cho mt kiu d liu c th nn chng ta khng th dng mt kiu d liu tng qut, cp ngoc nhn <> cng phi trng. Sau phn tn lp chng ta phi vit thm tn kiu d liu mun dng gia cp ngoc nhn <>. Khi chng ta chuyn bit ho mt kiu d liu cho mt mu chng ta cng phi nh ngha tt c cc thnh vin tng xng vi s chuyn mn ho (nu bn thy cha r lm, hy xem li v d trn trong chng ta phi vit li constructor cho chnh n mc d ci ny hon ton ging nh constructor trong lp tng qut. Nguyn nhn l do khng c thnh vin no c "tha k" t lp tng qut cho lp chuyn mn ho.

Cc gi tr tham s cho mu
Bn cnh cc tham s ca mu l kiu d liu (c ng trc bi t kho class hay typename), cc hm mu v cc lp mu cn c th c cc tham s khc khng phi l kiu m chng c th l cc gi tr hng. Trong v d di y lp mu c dng lu tr mng:

// array template #include <iostream.h> template <class T, int N> class array { T memblock [N]; public: setmember (int x, T value); T getmember (int x); }; template <class T, int N> array<T,N>::setmember (int x, T value) { memblock[x]=value; } template <class T, int N> T array<T,N>::getmember (int x) { return memblock[x]; } int main () { array <int,5> myints; array <float,5> myfloats; myints.setmember (0,100); myfloats.setmember (3.0,3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0; }

100 3.1416

Chng ta cng c th thit lp cc gi tr mc nh cho bt k tham s mu no ging nh vi cc tham s ca hm bnh thng. V d: template template template template template <class T> <class T, class U> <class T, int N> <class T = char> <int Tfunc (int)> // // // // // Trng hp ph bin nht: mt tham s lp. Hai tham s lp. Mt lp v mt gi tr nguyn. Mt tham s lp vi gi tr mc nh. Tham s l mt hm.

90

Mu v cc d n
Theo quan im ca trnh bin dch, cc mu khng phi l cc hm hay lp thng thng. Chng c dch theo nhu cu. iu c ngha l m ca mt hm mu khng c dch cho n khi cn dng n. Vi cc trnh dch thi im thc hin bi vit, trnh dch s to ra t mu mt hm c th cho kiu d liu c yu cu. Khi cc d n pht trin ln, n thng chi m ca mt chng trnh thnh nhiu file khc nhau. Trong nhng trng hp , ni chng phn giao tip v phn thc hin l tch bit. Ly v d mt th vin hm no , phn giao tip thng gm tt c nhng khai bo mu ca cc hm c th c gi, chng thng c khai bo trong mt "header file"vi phn m rng .h, v phn thc hin (phn nh ngha c cc hm ) c t trong cc file m C++ ring. i vi mu, chng ta c mt iu bt buc khi thc hin cc d n nhiu file: phn thc hin (phn nh ngha) ca mt lp mu hay hm mu phi nm trong cng mt file vi phn khai bo. iu ny c ngha l chng ta khng th tch phn giao tip thnh mt file ring m phi gp c phn giao tip v phn thc thi vo bt k fiel no s dng mu. Tr li vi trng hp th vin hm, nu chng ta mun to mt th vin hm mu, thay v vic to mt header file (.h) chng ta nn to mt "template file" cha c phn giao tip v phn thc thi ca cc hm mu (khng c mt quy nh no v phn m rng ca nhng file ny, bn thch dng th no cng c hoc c l .h cho tin). Mt iu cui cng na l vic mt "template file" c dng nhiu ln trong mt d n s khng gy ra li lin kt v chng c dch theo nhu cu v nhng trnh bin dch h tr templates s bit phi lm th no khng sinh m lp trong cc trng hp .

Bi 5.1

Namespaces

Namespaces cho php chng ta gp mt nhm cc lp, cc i tng ton cc v cc hm di mt ci tn. Ni mt cch c th hn, chng dng chia phm vi ton c thnh nhng phm vi nh hn vi tn gi namespaces. Khung mu s dng namespaces l:

namespace identifier { namespace-body }


Trong identifier l bt k mt tn hp l no v namespace-body l mt tp hp nhng lp, i tng v hm c gp trong namespace. V d:

namespace general { int a, b; } Trong trng hp ny, a v b l nhng bin bnh thng c tch hp bn trong namespace general. c th truy xut vo cc bin ny t bn ngoi namespace chng ta phi s dng ton t ::. V d, truy xut vo cc
bin chng ta vit:

general::a general::b
Namespace c bit hu dng trong trng hp c th c mt i tng ton cc hoc mt hm c cng tn vi mt ci khc, gy ra li nh ngha li. V d:

// namespaces #include <iostream.h>

5 3.1416

91

namespace first { int var = 5; } namespace second { double var = 3.1416; } int main () { cout << first::var << endl; cout << second::var << endl; return 0; }
Trong v d ny c hai bin ton cc cng c tn var, mt c nh ngha trong namespace first v ci cn li nm trong second. Chng trnh vn chy ngon, cm n namespaces.

using namespace
Ch th using theo sau l namespace dng kt hp mc truy xut hin thi vi mt namespace c th cc i tng v hm thuc namespace c th c truy xut trc tip nh th chng c khai bo ton cc. Cch s dng nh sau:

using namespace identifier;


V d:

// using namespace example #include <iostream.h> namespace first { int var = 5; } namespace second { double var = 3.1416; } int main () { using namespace second; cout << var << endl; cout << (var*2) << endl; return 0; }

3.1416 6.2832

Trong trng hp ny chng ta c th s dng var m khng phi t trc n bt k ton t phm vi no. Bn phi mt iu rng cu lnh using namespace ch c tc dng trong khi lnh m n c khai bo hoc trong ton b chng trnh nu n c dng trong phm vi ton cc. V d, nu chng ta nh u tin s dng mt i tng thuc mt namespace v sau s dng mt i tng thuc mt namespace khc chng ta c th lm nh sau:

// using namespace example #include <iostream.h>

5 3.1416

92

namespace first { int var = 5; } namespace second { double var = 3.1416; } int main () { { using namespace first; cout << var << endl; } { using namespace second; cout << var << endl; } return 0; }

nh ngha b danh
Chng ta cng c th nh ngha nhng tn thay th cho cc namespaces c khai bo. Cch thc lm vic ny nh sau:

namespace new_name = current_name ;

Namespace std
Mt trong nhng v d tt nht m chng ta c th tm thy v namespaces chnh l bn thn th vin chun ca C++. Theo chun ANSI C++, tt c nh ngha ca cc lp, i tng v hm ca th vin chun u c nh ngha trong namespace std. Bn c th thy rng chng ta b qua lut ny trong sut tutorial ny. Ti quyt nh lm vy v lut ny cng mi nh chun ANSI (1997) v nhiu trnh bin dch c khng tng thch vi n. Hu ht cc trnh bin dch, thm ch c nhng ci tun theo chun ANSI, cho php s dng cc file header truyn thng (nh l iostream.h, stdlib.h), nhng ci m chng ta trong sut tutorial ny. Tuy nhin, chun ANSI hon ton thit k li nhng th vin ny tn dng li th ca tnh nng templates v tun theo lut phi khai bo tt c cc hm v bin trong namespace std. Chun ANSI ch nh nhng tn mi cho nhng file "header" ny, c bn l dng cng tn vi cc file ca chun C++ nhng khng c phn m rng .h. V d, iostream.h tr thnh iostream. Nu chng ta s dng cc file include ca chun ANSI-C++ chng ta phi lun nh rng tt c cc hm, lp v i tng s c khai bo trong std. V d:

// ANSI-C++ compliant hello world #include <iostream> int main () {

Hello world in ANSI-C++

93

std::cout +\n"; return 0; }

<<

"Hello

world

in

ANSI-C+

Mc d vy chng ta nn s dng using namespace khi phi vit ton t :: khi tam chiu n cc i tng chun:

// ANSI-C++ compliant hello world (II) #include <iostream> using namespace std; int main () { cout << "Hello world in ANSI-C++\n"; return 0; }

Hello world in ANSI-C++

Bi 5.1

Exception handling

Trong sut qu trnh pht trin mt chng trnh, c th c mt s trng hp m mt s on m chy sai do truy xut n nhng ti nguyn khng tn ti hay vt ra ngoi khong mong mun... Nhng loi tnh hung bt thng ny c nm trong ci c gi l exceptions v C++ va tch hp ba ton t mi x l nhng tnh hung ny: try, throw v catch. Dng thc s dng nh sau:

Nguyn tc hot ng: - on m nm trong khi try c thc hin mt cch bnh thng. Trong trng hp c li xy ra, on m ny phi s dng t kho throw v mt tham s bo li. Kiu tham s ny m t chi tit ho li v c th l bt k kiu hp l no. - Nu c li xy ra, nu lnh throw c thc hin bn trong khi try, khi catch s c thc hin v nhn tham s c truyn bi throw. V d:

try { // on m cn th throw exception; } catch (type exception) { // on c thc hin trong trng hp c li }

// exceptions #include <iostream.h> int main () { char myarray[10]; try

Exception: Out of range

94

{ for (int n=0; n<=10; n++) { if (n>9) throw "Out of range"; myarray[n]='z'; }

} catch (char * str) { cout << "Exception: " << str << endl; } return 0;

Trong v d ny, nu bn trong vng lp m n ln hn 9 th mt li s c thng bo v myarray[n] trong trng hp c th tr n a ch nh khng tin cy. Khi throw c thc hin, khi try ngay lp tc kt thc v mi i tng c to bn trong khi try b ph hu. Sau , quyn iu khin c chuyn cho khi catch tng ng (ch c thc hin trong nhng tnh hung nh th ny). Cui cng chng trnh tip tc ngay sau khi, trong trng hp ny: return 0;. C php c s dng bi throw tng t vi return: Ch c mt tham s v khng cn t n nm trong cp ngoc n. Khi catch phi nm ngay sau khi try m khng c c on m no nm gia chng. Tham s m catch chp nhn c th l bt k kiu d liu hp l no. Hn na, catch c th c qu ti c th chp nhn nhiu kiu d liu khc nhau. Trong trng hp ny khi catch c thc hin l khi ph hp vi kiu ca tham s c gi n bi throw:

// exceptions: multiple catch blocks #include <iostream.h> int main () { try { char * mystring; mystring = new char [10]; if (mystring == NULL) throw "Allocation failure"; for (int n=0; n<=100; n++) { if (n>9) throw n; mystring[n]='z'; } } catch (int i) { cout << "Exception: "; cout << "index " << i << " is out of range" << endl; } catch (char * str) { cout << "Exception: " << str << endl; } return 0; }

Exception: index 10 is out of range

95

y c th c hai trng hp xy ra:

1. 2.

Khi d liu 10 k t khng th c cp pht (gn nh l chng bao gi xy ra nhng khng c ngha l khng th): li ny s b chn bi catch (to char * str). Ch s cc i ca mystring b vt qu: li ny s b chn bi catch (int i), since parameter is an integer number.

Chng ta c th nh ngha mt khi catch chn tt c cc exceptions m khng ph thuc vo kiu c dng gi throw. lm vic ny chng ta phi vit du ba chm thay v kiu v tn s tham s:

try { // code here } catch (...) { cout << "Exception occurred"; }


Cn c th lng cc khi try-catch vo cc khi try khc. Trong trng hp ny, mt khi catch bn trong c th chuyn tip exception nhn c cho khi bn ngoi, lm vic ny chng ta s dng biu thc throw; khng c tham s. V d:

try { try { // code here } catch (int n) { throw; } } catch (...) { cout << "Exception occurred"; }

Exception khng b chn


Nu mt exception khng b chn bi bt k lnh catch no v khng c lnh no c kiu ph hp, hm c bit terminate s c gi. Hm ny c nh ngha sn chm dt chng trnh ngay lp tc v hin thc thng bo li "Abnormal termination". Dng thc ca n nh sau:

void terminate();

Nhng exceptions chun


Mt s hm thuc th vin C++ chun gi cc exceptions m chng ta c th chn nu chng ta s dng mt khi try. Nhng exceptions ny c gi i vi kiu tham s l mt lp tha k t std::exception. Lp ny (std::exception) c nh ngha trong file header C++ chun <exception> v c dng lm mu cho h thng phn cp cc exception chun:

exception bad_alloc bad_cast bad_exception bad_typeid

(gi bi new) (gi bi dynamic_cast khi tht bi vi mt kiu tham chiu) (c gi khi mt exception khng ph hp vi lnh catch no) (gi bi typeid)

96

logic_error domain_error invalid_argument length_error out_of_range runtime_error overflow_error range_error underflow_error ios_base::failure (gi bi ios::clear)
Bi v y l mt h thng phn lp c th bc, nu bn s dng mt khi catch chn bt k mt exception no nm trong h thng ny bng cch s dng tham s bin (thm mt du & vo pha trc tn ca tham s) bn s chn c tt c cc exception tha k (lut tha k trong C++) V d di y chn mt exception c kiu bad_typeid (c tha k t exception), li ny c to ra khi mun bit kiu ca mt con tr null.

// Nhng exception chun #include <iostream.h> #include <exception> #include <typeinfo> class A {virtual f() {}; }; int main () { try { A * a = NULL; typeid (*a); } catch (std::exception& e) { cout << "Exception: " << e.what(); } return 0; }

Exception: pointer

Attempted

typeid

of

NULL

Bn c th s dng cc lp ca h thng phn cp cc exception chun ny bo nhng li ca mnh hoc tha k nhng lp mi t chng.

Bi 5.4

Chuyn i kiu nng cao

Cho n nay, c th chuyn i kiu mt i tng n gin sang kiu khc chng ta s dng ton t chuyn i kiu truyn thng. V d, chuyn mt s du phy ng c kiu double sang dng s nguyn c kiu int chng ta s dng:

int double i = (int) d;


hoc

i; d;

i = int (d);

97

iu ny lm vic tt i vi cc kiu c bn c nh ngha cc cacchs chuyn i c bn, tuy nhin nhng ton t ny cng c th c p dng ba bi vi cc lp v con tr ti cc lp. Bi vy, hon ton hp l khi vit nh sau:

// class type-casting #include <iostream.h> class CDummy { int i; }; class CAddition { int x,y; public: CAddition (int a, int b) { y=b; } int result() { return x+y;} }; int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd->result(); return 0; }
Mc d chng trnh trn l hp l trong C++ (thc t l n s c dch m khng c bt k mt li hay warning no i vi hu ht cc trnh dch) nhng n l mt on m khng tt lm v chng ta s dng hm result, l mt thnh vin ca CAddition, padd khng phi l mt i tng, n ch l mt con tr c chng ta gn cho a ch ca mt i tng khng c quan h. Khi truy xut n thnh vin result, chng trnh s to ra li run-time hoc ch l mt kt qu khng mong mun. c th iu khin vic chuyn i kiu gia cc lp, chun ANSI-C++ nh ngha bn ton t chuyn i kiu mi: reinterpret_cast, static_cast, dynamic_cast v const_cast. Tt c chng u c cng dng thc khi s dng:

x=a;

reinterpret_cast dynamic_cast static_cast const_cast Trong new_type kiu m

phi c chuyn i thnh. to ra s tng t d hiu vi cc ton t chuyn i truyn thng cc biu thc ny c ngha l:

<new_type> <new_type> <new_type> <new_type> expression

(expression) (expression) (expression) (expression)

(new_type) new_type (expression)

expression

reinterpret_cast
reinterpret_cast chuyn i mt con tr sang bt k kiu con tr no khc. N cng cho php chuyn i t
con tr sang dng s nguyn v ngc li. Ton t ny c th chuyn i con tr gia cc lp khng c quan h vi nhau. Kt qu ca ton t ny l mt bn copy gi tr ca con tr ny sang con tr kia. D liu c tr n khng h c kim tra hay chuyn i. Trong trng hp chuyn i gia con tr v s nguyn, cch chuyn ni dung ca n ph thuc vo h thng.

98

class class A * a B * b = reinterpret_cast<B*>(a);

A B = new

{}; {}; A;

reinterpret_cast i x vi tt c cc con tr ging nh cc ton t chuyn i truyn thng.

static_cast
static_cast cho php thc hin bt k php chuyn i no static_cast allows to perform any casting that can be implicitly performed as well as also the inverse cast
(even if this is not allowed implicitly). Applied to pointers to classes, that is to say that it allows to cast a pointer of a derived class to its base class (this is a valid conversion that can be implicitly performed) and can also perform the inverse: cast a base class to its derivated class. In this last case the base class that is being casted is not checked to determine wether this is a complete class of the destination type or not.

class Base class Derived: public Base * a = Derived * b = static_cast<Derived*>(a);

Base new

{}; {}; Base;

static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly
defined in classes, as well as to perform standard conversions between fundamental types:

double int i = static_cast<int>(d);

d=3.14159265;

dynamic_cast
dynamic_cast is exclusively used with pointers and references to objects. It allows any type-casting that can be
implicitly performed as well as the inverse one when used with polymorphic classes, however, unlike static_cast, dynamic_cast checks, in this last case, if the operation is valid. That is to say, it checks if the casting is going to return a valid complete object of the requested type. Checking is performed during run-time execution. If the pointer being casted is not a pointer to a valid complete object of the requested type, the value returned is a NULL pointer.

class class

Base Derived

{ :

virtual public

dummy(){}; Base {

}; };

Base* b1 = new Derived; Base* b2 = new Base; Derived* d1 = dynamic_cast<Derived*>(b1); // succeeds Derived* d2 = dynamic_cast<Derived*>(b2); // fails: returns NULL
If the type-casting is performed to a reference type and this casting is not possible an exception of type bad_cast is thrown:

99

class class

Base Derived

virtual public

dummy(){}; Base {

}; };

Base* b1 = new Derived; Base* b2 = new Base; Derived d1 = dynamic_cast<Derived&*>(b1); // succeeds Derived d2 = dynamic_cast<Derived&*>(b2); // fails: exception thrown

const_cast
This type of casting manipulates the const attribute of the passed object, either to be set or removed:

class const C * C * b = const_cast<C*> (a);

C a

new

{}; C;

Neither of the other three new cast operators can modify the constness of an object.

typeid
ANSI-C++ also defines a new operator called typeid that allows to check the type of an expression:

typeid (expression)
this operator returns a refernece to a constant object of type type_info that is defined in standard header file <typeinfo>. This returned value can be compared with another using operators == and != or can serve to obtain a string of characters representing the data type or class name by using its name() method.

// typeid, typeinfo #include <iostream.h> #include <typeinfo> class CDummy { }; int main () { CDummy* a,b; if (typeid(a) != typeid(b)) { cout << "a and b are of different types:\n"; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; } return 0; }

a and b are of a is: class b is: class CDummy

different types: CDummy *

100

Bi 1.1: Cu trc ca mt chng trnh C++.....................................................................................................1 Cc ch thch....................................................................................................................................................2 Bi 1.2: Cc bin, kiu v hng s.......................................................................................................................3 Identifiers.........................................................................................................................................................3 Cc kiu d liu...............................................................................................................................................3 Khai bo mt bin............................................................................................................................................4 Khi to cc bin.............................................................................................................................................5 Phm vi hot ng ca cc bin......................................................................................................................6 Cc hng s......................................................................................................................................................6 nh ngha cc hng (#define).........................................................................................................................8 Khai bo cc hng (const)................................................................................................................................9 Bi 1.3: Cc ton t.............................................................................................................................................9 Th t u tin ca cc ton t.......................................................................................................................13 Bi 1.4: Giao tip vi console..........................................................................................................................15 Xut d liu (cout).........................................................................................................................................15 Nhp d liu (cin)..........................................................................................................................................16 Bi 2.1 Cc cu trc iu khin........................................................................................................................18 Cu trc iu kin: if v else........................................................................................................................18 Cc cu trc lp..............................................................................................................................................19 Cc lnh r nhnh v lnh nhy.....................................................................................................................21 Cu trc la chn: switch..............................................................................................................................22 Bi 2.2 Hm (I)..................................................................................................................................................24 Cc hm khng kiu. Cch s dng void......................................................................................................27 Bi 2.3 Hm (II)................................................................................................................................................27 Truyn tham s theo tham s gi tr hay tham s bin..................................................................................28 Gi tr mc nh ca tham s.........................................................................................................................29 Qu ti cc hm..............................................................................................................................................30 Cc hm inline................................................................................................................................................31 qui.............................................................................................................................................................31 Khai bo mu cho hm..................................................................................................................................31 Bi 3.1 Mng.....................................................................................................................................................33 Khi to mt mng........................................................................................................................................34 Truy xut n cc phn t ca mng.............................................................................................................34 Mng nhiu chiu...........................................................................................................................................36 Dng mng lm tham s................................................................................................................................37 Bi 3.2 Xu k t..............................................................................................................................................39 Khi to cc xu k t....................................................................................................................................39 Gn gi tr cho xu k t................................................................................................................................40 Chuyn i xu k t sang cc kiu khc......................................................................................................42 Cc hm thao tc trn chui......................................................................................................................43 Bi 3.3 Con tr.................................................................................................................................................43 Ton t ly a ch (&)...................................................................................................................................44 Ton t tham chiu (*)...................................................................................................................................44 Khai bo bin kiu con tr.............................................................................................................................45 Con tr v mng.............................................................................................................................................47 Khi to con tr.............................................................................................................................................48 Cc php tnh s hc vi pointer...................................................................................................................49 Con tr tr ti con tr....................................................................................................................................50 Con tr khng kiu.........................................................................................................................................51 101

Con tr hm....................................................................................................................................................52 Bi 3.4 B nh ng........................................................................................................................................52 B nh ng trong ANSI-C...........................................................................................................................54 Bi 3.5 Cc cu trc..........................................................................................................................................56 Cc cu trc d liu.......................................................................................................................................56 Con tr tr n cu trc.................................................................................................................................58 Cc cu trc lng nhau...................................................................................................................................60 Bi 3.6 Cc kiu d liu t nh ngha.............................................................................................................60 T nh ngha cc kiu d liu (typedef)......................................................................................................61 Union..............................................................................................................................................................61 Cc unions v danh........................................................................................................................................62 Kiu lit k (enum)........................................................................................................................................63 Bi 4.1 Cc lp..................................................................................................................................................63 Constructors v destructors............................................................................................................................66 Qu ti cc Constructors................................................................................................................................67 Con tr ti lp................................................................................................................................................69 Cc lp c nh ngha bng t kho struct................................................................................................70 Bi 4.2 Qu ti cc ton t..............................................................................................................................70 T kho this....................................................................................................................................................72 Cc thnh vin tnh........................................................................................................................................73 Bi 4.3 Quan h gia cc lp............................................................................................................................74 Cc hm bn b (t kho friend)...................................................................................................................74 Cc lp bn b (friend)..................................................................................................................................75 S tha k gia cc lp..................................................................................................................................76 Nhng g c tha k t lp c s?............................................................................................................78 a tha k......................................................................................................................................................79 Bi 4.4 Cc thnh vin o. a hnh..................................................................................................................80 Con tr ti lp c s......................................................................................................................................80 Cc thnh vin o...........................................................................................................................................81 Tru tng ho lp c s..............................................................................................................................82 Bi 5.1 Templates............................................................................................................................................86 Cc mu hm..................................................................................................................................................86 Cc lp mu...................................................................................................................................................88 Chuyn mn ho mu....................................................................................................................................89 Cc gi tr tham s cho mu...........................................................................................................................90 Mu v cc d n...........................................................................................................................................91 Bi 5.1 Namespaces..........................................................................................................................................91 using namespace.............................................................................................................................................92 nh ngha b danh.........................................................................................................................................93 Namespace std................................................................................................................................................93 Bi 5.1 Exception handling..............................................................................................................................94 Exception khng b chn................................................................................................................................96 Nhng exceptions chun................................................................................................................................96 Bi 5.4 Chuyn i kiu nng cao...................................................................................................................97 reinterpret_cast...............................................................................................................................................98 static_cast.......................................................................................................................................................99 dynamic_cast..................................................................................................................................................99 const_cast.....................................................................................................................................................100 typeid............................................................................................................................................................100 102

103