Professional Documents
Culture Documents
jsp
Copyright vietjack.com
Mc lc
Hc C++ c bn v nng cao ............................................................................................... 9
i vi c gi ...................................................................................................................... 9
iu kin tin ................................................................................................................... 9
Tng quan v C++................................................................................................................ 9
Lp trnh hng i tng.............................................................................................. 10
Th vic chun C++ (C++ Standard Library) .................................................................. 10
ANSI Standard................................................................................................................ 10
Hc tp C++ nh th no? ............................................................................................. 10
Min s dng ca C++ ................................................................................................... 11
Ci t mi trng C++ ...................................................................................................... 11
Ci t mi trng ni b cho C++ ................................................................................. 11
Text Editor ...................................................................................................................... 11
C++ Compiler: ................................................................................................................ 11
Ci t GNU C/C++ Compiler......................................................................................... 12
Ci t trn UNIX/Linux .................................................................................................. 12
Ci t trn Mac OS X .................................................................................................... 12
Ci t trn Windows...................................................................................................... 12
C php C++ c bn .......................................................................................................... 13
Cu trc chng trnh C++ ............................................................................................. 13
Bin dch v thc thi chng trnh C++........................................................................... 14
Du chm phy v khi (block) trong C++ ...................................................................... 15
nh danh (Identifier) trong C++ ...................................................................................... 16
T kha trong C++ ......................................................................................................... 16
Trigraph trong C++.......................................................................................................... 17
Khong trng (Whitespace) trong C++............................................................................ 18
Comment trong C++........................................................................................................... 19
Kiu d liu trong C++ ........................................................................................................ 20
http://vietjack.com/ Trang chia s cc bi hc online min ph
Trang 1
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 2
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 3
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 4
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 5
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 6
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 7
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 8
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
i vi c gi
Lot bi hng dn v C++ c chun b cho ngi mi hc, gip h hiu cc khi nim C++ t
c bn ti nng cao.
iu kin tin
Trc khi bt u hc theo lot bi ny v thc hnh vi cc v d v C++ a dng, mnh gi s
rng bn bit khi nim v mt chng trnh my tnh l g v th no l mt ngn ng lp trnh
my tnh.
Trang 9
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Core Language cung cp tt c cc khi bao gm bin, kiu d liu (data type) v literals,
Th vin chun C++ (C++ Standard Library) cung cp tp hp hm a dng thao tc file,
string,
ANSI Standard
ANSI Standard bo m rng C++ l portable, ngha l: code bn vit cho compiler ca Microsoft
s c bin dch m khng xy ra li khi s dng mt compiler trn Mac, UNIX, v Windows box
hoc mt Alpha.
ANSI Standard tn ti trong thi gian di, v tt c C++ compiler u h tr ANSI Standard.
Hc tp C++ nh th no?
iu quan trng nht khi hc tp C++ l trng tm vo cc khi nim.
Mc ch ca vic hc mt ngn ng lp trnh l tr thnh mt lp trnh vin gii hn, tc l
thit k v thc thi cc h thng mi hiu qu hn, hoc sa i chng trnh c.
Trang 10
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
C++ h tr cc phong cch lp trnh a dng. Bn c th vit trong Fortran, C, Smalltalk, trong
bt k ngn ng no. Mi style c th t c mc tiu ca n mt cch hiu qu trong khi duy tr
runtime v space hiu qu.
Ci t mi trng C++
Ci t mi trng ni b cho C++
Nu bn mun ci t mi trng C++, bn cn hai phn mm c sn trong my sau y:
Text Editor
N s c s dng son chng trnh ca bn. V d nh Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS v Vim hoc Vi.
Tn v phin bn ca Text Editor c th a dng trn cc h iu hnh khc nhau. V d, Notepad
s c s dng trn Windows v Vim hoc Vi c th c s dng trn Windows cng nh Linux
hoc UNIX.
Cc file, m bn to vi editor ny, c gi l cc source file v vi C++, chng c t tn vi
ui m rng l .cpp, .cp, hoc .c.
Trc khi bt u lp trnh, m bo rng bn c mt Text editor v bn c kinh nghim
son mt chng trnh C++.
C++ Compiler:
C++ Compiler c s dng bin dch source code ca bn thnh chng trnh c th thc thi.
Trang 11
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Hu ht C++ compiler khng quan tm phn ui m rng bn cung cp cho source code, nhng
nu bn khng xc nh, th theo mc nh, n s s dng ui l .cpp.
Compiler c s dng thng xuyn nht l GNU C/C++ compiler, hoc bn c th s dng cc
Compiler khc t HP hoc Solaris nu bn c H iu hnh tng ng.
Nu
GCC
cha
ci
t,
bn
cn
phi
ci
theo
hng
dn
ti:http://gcc.gnu.org/install/
Ci t trn Mac OS X
Nu bn s dng Mac OS X, cch n gin nht ci t GCC l ti mi trng pht trin Xcode
t Website ca Applet v theo cc ch dn.
Bn c th ti Xcode t: developer.apple.com/technologies/tools/.
Ci t trn Windows
ci t GCC trn Windows, bn cn ci t MinGW. ci t MinGW, bn truy
cp:www.mingw.org, v t ti trang ti MinGW. Ti phin bn mi nht ca MinGW, s c
tn l MinGW-<version>.exe.
Trong khi ci t MinGW, ti thiu bn phi ci t gcc-core, gcc-g++, binutils, v MinGW runtime.
Trang 12
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
C php C++ c bn
Khi chng ta xem xt mt chng trnh C++, n c th c nh ngha nh l mt tp hp ca
cc i tng, m giao tip thng qua vic triu hi cc phng thc ca mi i tng . Di
y, chng ti miu t ngn gn ngha ca class (lp), object (i tng), method (phng thc)
v cc bin i tng:
Object - i tng c cc trng thi v hnh vi. V d: mt i tng dog c cc trng thi
l color, name, breed, v cc hnh vi l wagging, barking, eating. Mt i tng l mt
minh ha ca mt lp.
int main()
{
Trang 13
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Dng using namespace std; ni cho compiler s dng std namespace. Namespce l phn
b sung gn y cho C++.
Dng tip theo // main() is where program execution begins. l mt comment n dng
trong C++. Cc comment n dng bt u vi // v kt thc cui dng.
Dng tip theo cout << "This is my first C++ program."; lm thng bo This is my first
C++ program c hin th trn mn hnh.
Dng tip theo return 0; kt thc hm main() v lm n tr v gi tr 0 ti tin trnh ang gi.
Son 'g++ hello.cpp ' v nhn Enter bin dch code trn. Nu khng c li xy ra trong
code ca bn th dng nhc lnh s a bn ti dng tip theo v to a.out file c th thc
thi.
$ g++ hello.cpp
Trang 14
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
$ ./a.out
Hello World
Bn chc chn rng g++ l trong path ca bn v bn ang chy n trong th mc m cha
hello.cpp file.
Bn c th bin dch chng trnh C/C++ bi s dng makefile. bit thm chi tit, bn c th
truy cp: Makefile Tutorial.
Hai dng sau l tng ng, C++ khng quan tm bn t bao nhiu lnh trn mt dng. V d:
x = y;
y = y+1;
add(x, y);
L ging vi:
x = y; y = y+1; add(x, y);
Trang 15
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
zara
abc
move_name
a_123
myname50
_temp
a23b9
retVal
else
new
this
auto
enum
operator
throw
bool
explicit
private
true
break
export
protected
try
case
extern
public
typedef
catch
false
register
typeid
char
float
reinterpret_cast
typename
class
for
return
union
Trang 16
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
const
friend
short
unsigned
const_cast
goto
signed
using
continue
if
sizeof
virtual
default
inline
static
void
delete
int
static_cast
volatile
do
long
struct
wchar_t
double
mutable
switch
while
dynamic_cast
namespace
template
Thay th cho
??=
??/
Trang 17
http://vietjack.com/cplusplus/index.jsp
??'
??(
??)
??!
??<
??>
??-
Copyright vietjack.com
Phi c t nht mt Whitespace (thng l khong trng) gia int v age compiler c th phn
bit chng. Trong lnh:
fruit = apples + oranges;
Cc k t khong trng (Whitespace) gia fruit v =, hoc gia = v apples l khng cn thit; tuy
nhin, gip cho code ca bn d c hn, bn c th thm chng vo.
Trang 18
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
also
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Khi code trn c bin dch, n s b qua // prints Hello World v cui cng cho kt qu sau:
Hello World
Trang 19
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
*/
T kha
Boolean
bool
Character
char
Integer
int
Floating point
float
double
Trang 20
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Valueless
void
Wide character
wchar_t
signed
unsigned
short
long
Bng sau hin th kiu bin, lng b nh n dng lu gi tr trong b nh, v gi tr ln nht v
nh nht c th c lu gi vi cc kiu bin :
Kiu
rng bit
Dy gi tr
char
1byte
unsigned char
1byte
0 ti 255
signed char
1byte
-127 ti 127
int
4bytes
-2147483648 ti 2147483647
unsigned int
4bytes
0 ti 4294967295
signed int
4bytes
-2147483648 ti 2147483647
short int
2bytes
-32768 ti 32767
Trang 21
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Range
0 ti 65,535
Range
-32768 ti 32767
long int
4bytes
-2,147,483,647 ti 2,147,483,647
4bytes
4bytes
0 ti 4,294,967,295
float
4bytes
double
8bytes
long double
8bytes
wchar_t
2 or 4 bytes
1 wide character
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
Trang 22
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 23
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 24
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Kiu
Miu t
bool
char
int
float
Gi tr single floating-point
double
Gi tr double floating-point
void
Khng tr v gi tr no
wchar_t
C++ cng cho php nh ngha cc kiu bin khc, s c gii thch trong cc chng ti,
l: Enumeration, Pointer, Array, Reference, Data structure, v Class.
Tip theo l cch nh ngha, khai bo v s dng cc kiu bin a dng:
y, type phi l mt kiu d liu hp l trong C++, gm char, w_char, int, float, double, bool
hoc bt k i tng no m ngi dng t nh ngha, v variable_list c th cha mt hoc
nhiu tn Identifier (nh danh) phn bit nhau bi du phy. Sau y l mt s khai bo hp l
trong C++:
int
i, j, k;
Trang 25
http://vietjack.com/cplusplus/index.jsp
char
c, ch;
float
f, salary;
Copyright vietjack.com
double d;
V d:
extern int d = 3, f = 5;
// declaration of d and f.
int d = 3, f = 5;
byte z = 22;
char x = 'x';
Vi nh ngha m khng c phn khi to: cc bin c khi to vi NULL (tt c byte c gi tr
0); gi tr khi to ca tt c bin khc khng c nh ngha.
Trang 26
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
V d
Trong v d sau, mt bin c khai bo ti phn u chng trnh, nhng n c nh
ngha bn trong hm main.
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
Trang 27
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
30
23.3333
Ging khi nim p dng trn khai bo hm, bn cung cp tn hm ti thi im khai bo v nh
ngha thc s ca hm c th c cung cp bt c u. V d:
// function declaration
int func();
int main()
{
// function call
int i = func();
}
// function definition
int func()
{
return 0;
}
Cc bin l lvalue c th xut hin bn tri ca php gn. Cc Numeric literal (hng s) l rvalue
khng th c gn v khng th xut hin bn tri ca php gn. Di y l mt lnh hp l
trong C++:
Trang 28
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int g = 20;
Nhng lnh sau l khng hp l v s cho mt compile-time error (li ti thi im bin dch):
10 = 20;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
Trang 29
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
b = 20;
c = a + b;
cout << c;
return 0;
}
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
Trang 30
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
int
Trang 31
http://vietjack.com/cplusplus/index.jsp
char
'\0'
float
double
pointer
NULL
Copyright vietjack.com
Khi to bin mt cch chnh xc l mt s thc hnh tt, nu khng, i khi chng trnh s cho
kt qu khng mong i.
// Legal
215u
// Legal
Trang 32
http://vietjack.com/cplusplus/index.jsp
0xFeeL
// Legal
078
032UU
Copyright vietjack.com
// decimal
0213
// octal
0x4b
// hexadecimal
30
// int
30u
// unsigned int
30l
// long
30ul
// unsigned long
// Legal
314159E-5L
// Legal
510E
210f
.e55
Gi tr true
V gi tr false
Trang 33
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
ngha
\\
K t \
\'
K t '
\"
K t "
\?
K t ?
\a
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
Trang 34
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
\t
tab ngang
\v
tab dc
\ooo
S h c s 8 ca mt ti 3 k s
\xhh . . .
S h c s 16 ca mt hoc nhiu k s
int main()
{
cout << "Hello\tWorld\n\n";
return 0;
}
World
"hello, \
Trang 35
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
dear"
#define LENGTH 10
#define WIDTH
int main()
{
int area;
Trang 36
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main()
{
const int
LENGTH = 10;
const int
WIDTH
= 5;
Ghi ch: N l bc thc hnh tt cho bn khi nh ngha cc hng kiu ch hoa trong C++.
Trang 37
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
C++ cho php cc kiu d liu char, int v double c cc Modifier t trc chng. Mt Modifier
c s dng thng bo ngha ca kiu c s, gip cho n tng s chnh xc hn vi s cn
thit ca cc tnh hung a dng.
Di y l cc Modifier trong C++:
signed
unsigned
long
short
Cc Modifier l: signed, unsigned, long, v short c th c p dng cho kiu integer. Ngoi
ra, signed v unsigned c th c p dng cho kiu char, v long c th p dng cho kiu
double.
Cc Modifier l signed v unsigned cng c th c s dng nh l tin t cho cc Modifier
l long hoc short modifiers. V d: unsigned long int.
C++ cho php kiu khai bo tt khai bo cc unsigned, short, or long integer. Bn c th ch
n gin s dng t unsigned, short, hoc long, m khng cn int. V d sau minh ha hai khai
bo l hp l trong C++ khai bo cc bin unsigned integer:
unsigned x;
unsigned int y;
phn bit s khc nhau gia hai Modifier l signed integer v unsigned integer c thng dch
bi C++, bn nn chy chng trnh sau:
#include <iostream>
using namespace std;
Trang 38
http://vietjack.com/cplusplus/index.jsp
short int i;
Copyright vietjack.com
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
N s cho kt qu:
-15536 50000
ngha
const
i tng ca kiu const khng th b thay i bi chng trnh trong khi thc thi
volatile
restrict
auto
Trang 39
http://vietjack.com/cplusplus/index.jsp
register
static
extern
mutable
Copyright vietjack.com
miles;
Trang 40
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// Function declaration
void func(void);
main()
{
while(count--)
{
func();
}
return 0;
}
// Function definition
void func( void )
{
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
Trang 41
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int count ;
extern void write_extern();
main()
Trang 42
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
{
count = 5;
write_extern();
}
void write_extern(void)
{
std::cout << "Count is " << count << std::endl;
}
y, t kha extern ang c s dng khai bo count trong file khc. By gi bin dch hai
file ny nh sau:
$g++ main.cpp support.cpp -o write
N s to chng trnh write c th thc thi, bn th thc thi write v kim tra kt qu nh sau:
$./write
5
Ton t s hc
Trang 43
http://vietjack.com/cplusplus/index.jsp
Ton t quan h
Ton t logic
Ton t gn
Ton t hn hp
Copyright vietjack.com
Miu t
V d
A + B kt qu l 30
A - B kt qu l -10
A * B kt qu l 200
Php chia
B / A kt qu l 2
Php ly s d
B % A kt qu l 0
++
A++ kt qu l 11
--
A-- kt qu l 9
Trang 44
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
V d
==
(A == B) l khng ng
!=
(A != B) l true
>
(A > B) l khng ng
<
(A < B) l true
>=
(A >= B) l khng ng
<=
(A <= B) l true
Trang 45
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Gi s bin A c gi tr 1 v bin B c gi tr 0:
V d
Ton
t
Miu t
V
d
&&
(A
&&
B) l
false.
||
(A ||
B) l
true.
!(A
&&
B) l
true.
p&q
p|q
p^q
Trang 46
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
V d
&
(A &
B) s
cho
kt
qu
l 12,
tc l
0000
1100
(A |
B) s
cho
kt
qu
l 61,
tc l
Trang 47
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
0011
1101
(A ^
B) s
cho
kt
qu
l 49,
tc l
0011
0001
(~A )
s
cho
kt
qu
l 61,
tc l
1100
0011.
<<
Ton t dch tri. Gi tr ton hng tri c dch chuyn sang tri bi s cc
bit c xc nh bi ton hng bn phi.
A <<
2 s
cho
kt
qu
240,
tc l
1111
0000
(dch
sang
tri
hai
bit)
>>
Ton t dch phi. Gi tr ton hng tri c dch chuyn sang phi bi s
A >>
2 s
Trang 48
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
cho
kt
qu
l 15,
tc l
0000
1111
(dch
sang
phi
hai
bit)
Miu t
V d
C=A
+ B s
gn
gi tr
ca A
+B
vo
trong
C
+=
C +=
A
tng
ng
vi C
=C+
A
Trang 49
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
-=
C -= A
tng
ng
vi C
=CA
*=
C *= A
tng
ng
vi C
=C*
A
/=
Chia ton hng tri cho ton hng phi v gn gi tr ny cho ton hng tri.
C /= A
tng
ng
vi C
=C/
A
%=
Ly phn d ca php chia ton hng tri cho ton hng phi v gn cho
ton hng tri.
C %=
A
tng
ng
vi C
=C%
A
<<=
C <<=
2
tng
ng
vi C
=C
<< 2
>>=
C >>=
2
tng
Trang 50
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
ng
vi C
=C
>> 2
&=
C &=
2
tng
ng
vi C
=C&
2
^=
C ^= 2
tng
ng
vi C
=C^
2
|=
Php OR bit.
C |= 2
tng
ng
vi C
=C|2
Miu t
sizeof
iu kin ? X : Y
Trang 51
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Cast
&
Ton t
Th t u tin
Postfix
() [] -> . ++ - -
Unary
Trang 52
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Tnh nhn
*/%
Tnh cng
+-
Dch chuyn
<< >>
Quan h
Cn bng
== !=
&
Php OR bit
&&
Php OR logic
||
iu kin
?:
Gn
Du phy
Trang 53
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Ngn ng lp trnh cung cp cho chng ta nhiu cu trc iu khin v cho php bn thc hin
nhng phn phc tp.
Vng lp cho php thc hin mt lnh v mt nhm lnh nhiu ln , di y l dng tng qut:
C++ h tr nhng lnh iu khin sau y. Click chut vo link xem chi tit.
Vng lp
Miu t
C++
Vng
lp
do...while
trong C++
Trang 54
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
C++
Miu t
Lnh
continue
trong
C++
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
Trang 55
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Khi biu thc iu kin vng mt, n c gi s l lun ng. Bn c th c mt biu thc khi
to v biu thc lng gia, nhng cc lp trnh vin C++ thng s dng for(;;) biu th mt
vng lp v hn.
Ghi ch: Bn c th dng (kt thc) mt vng lp v hn bi nhn Ctrl + C.
Di y lit k cc lnh iu khin lung c cung cp bi C++. Bn click vo link thy chi
tit.
Trang 56
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Lnh
Miu t
C++
Trong Exp1, Exp2 v Exp3 l cc biu thc. Ch vic s dng v t ca du hai chm.
Gi tr ca biu thc Exp1 trc du ? c gi tr true, Exp2 c thc hin, v gi tr ca n l gi
tr ca biu thc. Nu Exp1 l false th Exp3 c thc hin v gi tr ca n l gi tr ca biu
thc.
Hm trong C++
Mt hm l mt nhm cc lnh i cng nhau thc hin mt nhim v. Mi chng trnh C++ c
t nht mt hm l hm main(), v tt c hu ht cc chng trnh bnh thng u nh ngha
thm cc hm.
Trang 57
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Danh sch tham s: Khi hm c gi, bn phi truyn vo danh sch cc tham s. Mt
gi tr hng n mt tham s thc t. Danh sch tham s c cc kiu, th t v s lng
cc tham s ca hm. Cc tham s trong hm l ty chn, ngha l mt hm c th khng
c tham s.
Trang 58
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
V d
Sau y l m ngun cho mt hm c tn gi l max(). Hm ny c 2 tham s: num1 v num2 v
tr v gi tr ln nht gia hm s:
// function returning the max between two numbers
return result;
}
Tn cc tham s khng quan trng trong vic khai bo hm, nhng kiu di y l cch khai bo
hp l:
Trang 59
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Gi hm trong C++
Trong khi to mt hm, bn nh ngha nhng g hm phi lm. s dng mt hm, bn phi gi
hm thc hin mt nhim v c th.
Khi mt chng trnh gi mt hm, phn iu khin c chuyn n hm c gi. Mt hm
c gi thc hin cc nhim v c nh ngha v tr v gi tr sau khi thc hin chng trnh.
gi hm, bn n gin cn truyn cc tham s c yu cu cng vi tn ca hm v nu hm
tr v cc gi tr, bn c th d tr cc gi tr tr v ny, v d:
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
Trang 60
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return result;
}
Gi hm bi gi tr
trong C++
Gi hm bi con tr
Miu t
Trang 61
http://vietjack.com/cplusplus/index.jsp
trong C++
Gi
hm
Copyright vietjack.com
bi
tham
Theo mc nh, C++ s dng gi bi gi tr truyn cc tham s. Nhn chung, code trong mt
hm khng th thay i cc tham s c dng gi hm v trong v d trn, khi gi hm
max() l dng phng thc tng t.
result = a + b;
return (result);
}
int main ()
{
// local variable declaration:
Trang 62
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int a = 100;
int b = 200;
int result;
return 0;
}
int main ()
{
Trang 63
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// number definition:
short
s;
int
i;
long
l;
float
f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short
return 0;
}
s :10
int
i :1000
long
l :1000000
float
f :230.47
double d :30949.4
Trang 64
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Hm & Mc ch
double cos(double);
Hm ny tr v cosin ca mt gc (dng mt double)
double sin(double);
Hm ny tr v sin ca mt gc (dng mt double)
double tan(double);
Hm ny tr v tang ca mt gc (dng mt double)
double log(double);
Hm ny tr v logarit t nhin (ln) ca s
Trang 65
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
double sqrt(double);
Tr v cn bc hai ca s double
int abs(int);
Tr v tr tuyt i ca int
double fabs(double);
Tr v tr tuyt i ca bt k s double no
double floor(double);
10
int main ()
{
// number definition:
short
s = 10;
int
i = -1000;
long
l = 100000;
float
f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i)
Trang 66
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
:1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
int main ()
{
int i,j;
Trang 67
http://vietjack.com/cplusplus/index.jsp
/* generate 10
Copyright vietjack.com
random numbers. */
return 0;
}
Trang 68
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 69
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
Trang 70
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Chng trnh ny s dng hm setw() trong C++ nh dng output. Khi on code ny c
bin dch v thc hin, kt qu sau y s c in ra:
Element
Value
100
101
102
103
104
105
106
107
108
109
Miu t
Truyn mng ti hm nh l
tham s trong C++
Trang 71
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Thc t, bn khng t k t null ti v tr cui cng ca bin hng s. B bin dch C t ng thm
\0 ti v tr cui cng ca chui khi n khi to chui. Cng th v d in ra chui sau y:
#include <iostream>
Trang 72
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
Hm & Mc ch
strcpy(s1, s2);
Sao chp chui s2 cho chui s1.
strcat(s1, s2);
Ni chui s2 vo cui chui s1.
strlen(s1);
Tr v di ca chui s1.
strcmp(s1, s2);
Tr v 0 nu s1 v s2 l nh nhau; nh hn 0 nu s1<s2; ln hn 0 nu s1>s2.
Trang 73
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
strchr(s1, ch);
strstr(s1, s2);
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int
len ;
return 0;
Trang 74
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int
len ;
Trang 75
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
10
int main ()
{
int
var1;
char var2[10];
Trang 76
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Con tr l g?
Mt con tr l mt bin m trong gi tr ca n l a ch ca bin khc. V d nh a ch ca
vng nh. Ging nh cc bin v hng s, bn phi khai bo con tr trc khi bn c th s dng
n lu tr bt k a ch ca bin no. Dng tng qut ca vic khai bo con tr nh sau:
type *var-name;
*ip;
// pointer to an integer
double *dp;
// pointer to a double
float
*fp;
// pointer to a float
char
*ch
// pointer to character
Kiu d liu thc s ca gi tr ca tt c cc con tr, c th l integer, float, character, hoc kiu
khc, l ging nh, mt s long hexa biu din mt a ch b nh. im khc nhau duy nht ca
cc con tr ca cc kiu d liu khc nhau l kiu d liu ca bin hoc hng s m con tr ch ti.
Trang 77
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
int
var = 20;
int
*ip;
// pointer variable
ip = &var;
return 0;
}
Trang 78
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
Trang 79
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Bn khng th c tham chiu NULL. Bn lun lun phi gi s rng mt tham chiu c
kt ni vi mt phn ca kho lu tr.
i = 17;
r = i;
c & trong cc khai bo ny l Tham chiu. V th, trong khai bo u tin, r l tham chiu
integer c khi to cho i v trong tham chiu th hai, s l tham chiu double c khi to cho
d. V d sau s dng cc tham chiu trong C++:
#include <iostream>
int main ()
{
// declare simple variables
Trang 80
http://vietjack.com/cplusplus/index.jsp
int
Copyright vietjack.com
i;
double d;
r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r
<< endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s
<< endl;
return 0;
}
Tham chiu trong C++ thng c s dng cho danh sch cc tham s hm v hm tr v cc
gi tr. Sau y l hai khi nim quan trng lin quan ti tham chiu trong C++, bn s thy chi tit
khi click vo link:
Khi nim
Miu t
trong C++
Trang 81
http://vietjack.com/cplusplus/index.jsp
Tr v gi tr bi tham chiu
Copyright vietjack.com
trong C++
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
Bng di lit k cc hm quan trng trong khi bn lm vic vi Date v Time trong C hoc C++.
Tt v hm ny l mt phn ca th vin C v C++ chun v bn c th kim tra chi tit bi s
dng tham chiu ti Th vin chun C++ c cung cp di y:
STT
Hm & Mc ch
Trang 82
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
clock_t clock(void);
Hm ny tr v mt gi tr m xp x vi lng thi gian ca chng trnh ang gi
ang chy. Tr v -1 nu thi gian l khng c sn
Trang 83
http://vietjack.com/cplusplus/index.jsp
9
Copyright vietjack.com
size_t strftime();
Hm ny c th c s dng nh dng Date v Time trong mt nh dng c th
int main( )
{
// current date/time based on current system
time_t now = time(0);
cout << "The local date and time is: " << dt << endl;
8 20:07:41 2011
9 03:07:41 2011
Trang 84
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main( )
{
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970:" << now << endl;
tm *ltm = localtime(&now);
Trang 85
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Year: 2011
Month: 1
Day: 8
Time: 22: 44:59
Miu t
<iostream>
<iomanip>
<fstream>
Trang 86
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main( )
{
char str[] = "Hello C++";
B bin dch C++ cng quyt nh kiu d liu ca bin c output v chn ton t chn lung
thch hp hin th gi tr. Ton t << c np chng (overload) ti d liu u ra ca kiu
integer, float, double, string, v gi tr con tr c sn.
Ton t chn lung << c th c s dng nhiu hn mt ln trong mt lnh v endl c s
dng them mt dng mi ti cui dng .
Trang 87
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main( )
{
char name[50];
Khi code trn c bin dch v thc thi, n s nhc bn nhp mt tn. Bn nhp mt gi tr v sau
enter thy kt qu ging nh sau:
Please enter your name: cplusplus
Your name is: cplusplus
B bin dch C++ cng quyt nh kiu d liu ca gi tr nhp v chn ton t trch lung thch
hp trch gi tr v lu gi n trong cc bin cung cp.
Ton t trch lung >> c th c s dng nhiu hn mt ln trong mt lnh. yu cu nhiu
hn mt d liu chun, bn c th s dng:
cin >> name >> age;
Trang 88
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main( )
{
char str[] = "Unable to read....";
int main( )
{
char str[] = "Unable to read....";
Trang 89
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Bn s khng th thy bt k im khc bit no gia cout, cerr v clog vi nhng v d nh ny,
nhng trong khi vit v thc thi cc chng trnh ln, th s khc nhau ny tr nn r rng hn. V
th, n l bi thc hnh tt cho bn hin th cc thng bo li (error message) bi s dng
lung cerr v trong khi hin th thng bo log khc, th clog nn c s dng.
Title
Author
Subject
Book ID
Trang 90
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
}book;
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
Trang 91
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
Trang 92
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Book 2 id : 6495700
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
Trang 93
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
void printBook( struct Books book )
{
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
Trang 94
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
struct Books
{
char
title[50];
char
author[50];
char
subject[100];
int
book_id;
};
int main( )
{
struct Books Book1;
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
Trang 95
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book )
{
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
Trang 96
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
title[50];
char
author[50];
char
subject[100];
int
book_id;
}Books;
Bn c th s dng t kha typedef trong C++ cho cc dng khng phi cu trc, nh sau:
typedef long int *pint32;
pint32 x, y, z;
Trang 97
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
T kha public quyt nh cc thuc tnh truy cp ca cc thnh vin lp m theo sau n. Mt
thnh vin public c th c truy cp t bn ngoi lp bt c u bn trong phm vi (scope) ca
i tng lp . Bn cng c th xc nh cc thnh vin ca lp l privatehoc protected s
c bn lun trong chng ph.
Box Box2;
C hai i tng Box1 v Box2 s c bn sao ca cc thnh vin d liu (Data Member) ring.
Trang 98
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
class Box
{
public:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main( )
{
Box Box1;
Box Box2;
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Trang 99
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Miu t
Mt hm thnh vin ca mt lp l mt hm c nh
ngha ca n hoc prototype ca n bn trong nh
ngha lp ging nh bt k bin no khc
Mt thnh vin lp c th c nh ngha l public,
private hoc protected. Theo mc nh, cc thnh vin
s l private
Mt class constructor l mt hm c bit trong mt lp
m c gi khi mt i tng mi ca lp c
to. Mt class destructor cng l mt hm c bit m
c gi khi i tng to b hy
Trang 100
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 101
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
Trang 102
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
Trang 103
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Truy cp
public
protected
private
Trong cng lp
Lp k tha
Khng
Bn ngoi lp
Khng
Khng
Hm friend ca lp c s.
Trang 104
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 105
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
public:
int getCost(int area)
{
return area * 70;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
Trang 106
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
class printData
{
Trang 107
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double
f) {
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
return 0;
}
Trang 108
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Khai bo ton t + cng hai i tng Box v tr v i tng Box cui cng. Hu ht ton t
np chng c th c nh ngha di dng: cc hm khng c thnh vin (non-member) hoc
cc hm thnh vin lp. Trong trng hp trn, chng ta nh ngha hm dng non-member ca
mt lp, th sau chng ta phi truyn hai tham s cho mi ton hng, nh sau:
Box operator+(const Box&, const Box&);
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
Trang 109
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
// Main function for the program
int main( )
{
Box Box1;
Box Box2;
Box Box3;
Trang 110
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
Trang 111
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
&
<
>
<=
>=
++
--
<<
>>
==
!=
&&
||
+=
-=
/=
%=
^=
&=
|=
*=
<<=
>>=
[]
()
->
->*
new
new []
delete
delete []
.*
?:
Ton t v V d
Trang 112
http://vietjack.com/cplusplus/index.jsp
2
Copyright vietjack.com
class Shape {
protected:
int width, height;
public:
Trang 113
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 114
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Rectangle rec(10,7);
Triangle
tri(10,5);
return 0;
}
Trang 115
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
Sau khi sa i, khi code ca v d trn c bin dch v thc thi, n s cho kt qu sau:
Rectangle class area
Triangle class area
Trang 116
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};
Trang 117
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
thao tc vi tnh nng ca i tng v thao tc d liu i tng, v d: trng thi m khng
cn thc s bit v cch lp c trin khai ni ti.
V d, chng trnh ca bn c th to mt li gi ti hm sort() m khng cn bit v hm
thc s s dng thut ton g sp xp cc gi tr cho. Thc ra, trnh trin khai c s
(underlying implementation) ca tnh nng sp xp c th thay i ty vo th vin, v min l
Interface vn nh c th li gi hm ca bn vn tip tc lm vic.
Trong C++, chng ta s dng cc Lp nh ngha kiu d liu tru tng (abstract data types
(ADT)) ca ring chng ta. Bn c th s dng i tng cout ca lp ostream cho lung d liu
ti u ra chun nh sau:
#include <iostream>
using namespace std;
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}
Trang 118
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trin khai lp c th tin hnh qua thi gian p ng yu cu thay i hoc bug cc bo
co m khng yu cu thay i trong code ca ngi dng.
Bng vic nh ngha cc thnh vin d liu ch trong khu vc private ca lp, tc gi ca lp c
th t do to cc thay i trong d liu. Nu trnh trin khai thay i, th ch m ha lp l cn kim
tra bit kha cnh no em li thay i. Nu d liu l public, th khi bt k hm no m truy
cp mt cch trc tip ti cc thnh vin d liu ca php biu din c c th b ph v.
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
Trang 119
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
a.addNum(10);
a.addNum(20);
a.addNum(30);
Lp trn cng hai s v tr v tng ca chng. Cc thnh vin public l addNum vgetTotal l cc
Interface ti bn ngoi v mt ngi s dng cn bit chng s dng lp . Thnh vin
private l total l ci g m ngi s dng khng cn bit n, nhng l cn thit cho lp
hot ng mt cch chnh xc.
Trang 120
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trong trng hp ny, bt k chng trnh no ang s dng cc Interface ny, chng s khng b
nh hng v s cn mt s ti bin dch vi Implementation mi nht ny.
Cc lnh (code) chng trnh: y l phn chng trnh m thc hin cc hnh ng v
cng c gi l cc hm.
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
Trang 121
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
};
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
Trang 122
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
Lp trn cng hai s v tr v tng ca chng. Cc thnh vin public l addNum vgetTotal l cc
Interface ti bn ngoi v mt ngi s dng cn bit chng s dng lp . Thnh vin
private l total l ci g m ngi s dng khng cn bit n, nhng l cn thit cho lp
hot ng mt cch chnh xc.
Trang 123
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Mt Interface miu t hnh vi hoc kh nng ca mt lp trong C++ m khng k thc ti mt trnh
trin khai c th ca lp .
Interface trong C++ c trin khai bi s dng cc Lp tru tng (Abstract class) v nhng
lp tru tng ny khng nn b nhm ln vi Tru tng ha d liu, m l mt khi nim ca
vic gi Implementation Detail phn bit vi d liu c lin kt.
Mt lp c to l abstract bng vic khai bo t nht mt ln cc hm ca n l hm pure
virtual. Mt hm pure virtual c xc nh bng vic t = 0 trong khai bo ca n, nh sau:
class Box
{
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
Trang 124
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
#include <iostream>
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
Trang 125
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle
Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
Trang 126
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
ofstream
ifstream
fstream
thc hin tin trnh x l file trong C++, bn bao cc header file l <iostream> v <fstream>
trong source file ca chng trnh C++ ca bn.
Trang 127
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
ios::app
ios::ate
ios::in
M mt file c
ios::out
M mt file vit
ios::trunc
Bn c th kt hp hai hoc nhiu gi tr ny bng vic hoc chng cng vi nhau (s dng (|). V
d, nu bn mun m mt file trong ch vit v mun ct (truncate) n trong trng hp n
tn ti, bn theo c php sau:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Trang 128
http://vietjack.com/cplusplus/index.jsp
fstream
Copyright vietjack.com
afile;
int main ()
{
Trang 129
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
char data[100];
Trang 130
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
Khi code trn c bin dch v thc thi, n s cho input v output nh sau:
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Trang 131
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 132
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Bn c th lit k nhiu lnh catch bt cc kiu exception khc nhau trong trng hp
khi try ca bn xut hin nhiu hn mt exception trong cc tnh hung khc nhau.
Trang 133
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 134
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Bi v chng ta ang to mt exception c kiu const char*, v th trong khi bt exception ny,
chng ta phi s dng const char* trong khi catch. Nu chng ta bin dch v chy code trn, n
s cho kt qu sau:
Division by zero condition!
Trang 135
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
std::exception
std::bad_alloc
C th c nm bi new
std::bad_cast
C th c nm bi dynamic_cast
std::bad_exception
Trang 136
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
std::bad_typeid
C th c nm bi typeid
std::logic_error
std::domain_error
std::invalid_argument
c nm do cc tham s khng hp l
std::length_error
c nm khi mt std::string qu ln c to ra
std::out_of_range
std::runtime_error
std::overflow_error
std::range_error
std::underflow_error
Trang 137
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//Other errors
}
}
N s cho kt qu sau:
MyException caught
C++ Exception
Trang 138
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
B nh ng trong C++
Mt s hiu bit su v cch b nh ng thc s lm vic trong C++ l ct yu tr thnh mt
lp trnh vin C++ gii. B nh trong chng trnh C++ ca bn c phn thnh hai phn:
Nhiu khi, bn khng bit trc bao nhiu b nh bn s cn lu thng tin c th trong mt
bin c nh ngha v kch c b nh cn thit c th c quyt nh ti run time.
Bn c th cp pht b nh ti run time bn trong Heap cho bin vi mt kiu cho bi s
dng mt ton t c bit trong C++ m tr v a ch ca khng gian cp pht. Ton t ny gi
l ton t new trong C++.
Nu bn khng cn thit b nh ng cp pht na, bn c th s dng ton t deletetrong
C++, s gii phng b nh c cp pht trc bi ton t new.
= new double;
= NULL;
= new double ))
Trang 139
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
{
cout << "Error: out of memory." <<endl;
exit(1);
By gi, da vo cc khi nim trn chng ti to mt v d minh ha cch ton t new v delete
trong C++ lm vic:
#include <iostream>
using namespace std;
int main ()
{
double* pvalue
pvalue
= new double;
*pvalue = 29494.99;
delete pvalue;
return 0;
}
Trang 140
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
= NULL;
= NULL;
Tuy nhin, c php gii phng b nh cho mng a chiu vn ging trn:
delete [] pvalue;
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
Trang 141
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main( )
{
Box* myBoxArray = new Box[4];
return 0;
}
Trang 142
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 143
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Trang 144
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main ()
{
return 0;
}
using namespace directive trong C++ cng c th c s dng tham chiu mt item c th
trong mt namespace. V d, nu bn ch c nh s dng mt phn cout ca std namespace,
bn c th tham chiu n nh sau:
using std::cout;
Phn code theo sau c th tham chiu ti cout m khng cn ph thm vo sau namespace,
nhng cc item khc trong std namespace vn cn phi r rng, nh sau:
#include <iostream>
using std::cout;
int main ()
{
Trang 145
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Cc tn c gii thiu trong mt using namespace directive tun theo cc qui tc phm vi
(scope rule). Tn l nhn thy bt u t v tr ca using namespace directive ti phn cui ca
phm vi m trong directive ny c thy. Cc thc th vi cng tn c nh ngha trong
phm vi bn ngoi b n.
Trang 146
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Bn c th truy cp cc thnh vin ca namespace lng nhau ny bi s dng ton t phn gii
phm vi (resolution operator) trong C++, nh sau:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
Trang 147
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Function Template: l mt khun mu hm, cho php nh ngha cc hm tng qut thao
tc cho nhiu kiu d liu.
Class template: l mt khun mu lp, cho php nh ngha cc lp tng qut cho nhiu
kiu d liu
Trang 148
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
Trang 149
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
// elements
Trang 150
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
public:
void push(T const&);
// push element
void pop();
// pop element
T top() const;
return elems.empty();
}
};
Trang 151
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return elems.back();
}
int main()
{
try {
Stack<int>
intStack;
Stack<string> stringStack;
// stack of ints
// stack of strings
Trang 152
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Khi dng ny xut hin trong mt file, tt c macro xut hin theo sau trong file ny s c thay
th bi replacement-text trc khi chng trnh c bin dch. V d:
#include <iostream>
using namespace std;
#define PI 3.14159
int main ()
{
return 0;
}
Trang 153
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
...
int main ()
{
return 0;
}
int main ()
{
int i, j;
i = 100;
j = 30;
cout <<"The minimum is " << MIN(i, j) << endl;
return 0;
}
Trang 154
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Lnh cerr c bin dch trong chng trnh nu biu tng hng DEBUG c nh ngha
trc ch th #ifdef DEBUG. Bn c th s dng lnh #if 0 ch thch mt phn ca chng
trnh, nh sau:
#if 0
code prevented from compiling
#endif
Bn th v d sau:
#include <iostream>
using namespace std;
#define DEBUG
int main ()
{
int i, j;
i = 100;
Trang 155
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
#define MKSTR( x ) #x
Trang 156
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
cout << MKSTR(HELLO C++) << endl;
return 0;
}
By gi, chng ta xt cch n lm vic. N l n gin hiu rng b tin x l C++ chuyn
dng sau:
cout << MKSTR(HELLO C++) << endl;
Thnh dng:
cout << "HELLO C++" << endl;
x ## y
Khi CONCAT xut hin trong chng trnh, cc tham s ca n c ni chui v c s dng
thay th cho macro. V d, CONCAT(HELLO, C++) c thay th bi "HELLO C++" trong
chng trnh sau:
#include <iostream>
using namespace std;
#define concat(a, b) a ## b
int main()
{
int xy = 100;
Trang 157
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Gi chng ta xt cch chng lm vic. n gin l b tin x l C++ chuyn dng sau:
cout << concat(x, y);
Thnh dng:
cout << xy;
Miu t
__LINE__
__FILE__
__DATE__
__TIME__
int main ()
Trang 158
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
{
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
Miu t
SIGABRT
SIGFPE
SIGILL
Trang 159
http://vietjack.com/cplusplus/index.jsp
SIGINT
SIGSEGV
SIGTERM
Copyright vietjack.com
Hm ny nhn hai tham s: tham s u tin l mt integer m biu din s hiu tn hiu (signal
number) v tham s th hai l mt con tr ti hm x l tn hiu.
By gi, vit mt chng trnh C++ n gin bt tn hiu SIGINT bi s dng
hmsignal() trong C++. Bt c tn hiu no bn mun bt trong chng trnh, bn phi ghi tn hiu
bi s dng hm signal v lin kt n vi mt Signal Handler. Bn xt v d:
#include <iostream>
#include <csignal>
exit(signum);
Trang 160
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1){
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
By gi, nhn CTRL+C ngt chng trnh v bn s thy rng chng trnh s bt tn hiu ny
v s in ci g nh sau:
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
Trang 161
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
y, sig l signal number gi bt k loi tn hiu no: SIGINT, SIGABRT, SIGFPE, SIGILL,
SIGSEGV, SIGTERM, SIGHUP. Di y l v d to mt tn hiu ni ti bi s dng hm raise()
trong C++, nh sau:
#include <iostream>
#include <csignal>
exit(signum);
int main ()
{
int i = 0;
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(++i){
cout << "Going to sleep...." << endl;
if( i == 3 ){
raise( SIGINT);
}
sleep(1);
}
Trang 162
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Trang 163
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Miu t
thread
attr
start_routine
arg
Trang 164
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
V d
V d n gin sau to 5 thread vi chng trnh pthread_create(). Mi thread in mt thng bo
Hello World!, v sau kt thc vi mt li gi ti pthread_exit() trong C++:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#define NUM_THREADS
int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
Trang 165
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
}
pthread_exit(NULL);
}
#define NUM_THREADS
struct thread_data{
int
thread_id;
Trang 166
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
char *message;
};
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
Trang 167
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
pthread_exit(NULL);
}
Chng trnh con pthread_join() ng khi thread ang gi ti khi threadid kt thc. Khi mt thread
c to, mt trong cc thuc tnh nh ngha n l joinable hoc detached. Ch cc thread c
to vi dng joinable c th c kt hp. Nu mt thread c to vi dng detached, n khng
bao gi c kt hp.
V d sau minh ha cch i cho cc thread kt thc bi s dng chng trnh kt hp Pthread
trong C++:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
Trang 168
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
#define NUM_THREADS
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << "
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
Trang 169
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Trang 170
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Sleeping in thread
Thread with id : 3 .... exiting
Sleeping in thread
Thread with id : 4 .... exiting
Main: completed thread id :0
Web Browsing
hiu khi nim v CGI, chng ta xem nhng g xy ra khi chng ta nhn vo mt hyperlink
ti mt Webpage hoc URL c th.
Trnh duyt Web nhn phn hi t Web Server v hin th file nhn c hoc thng bo
li da trn phn hi nhn.
Trang 171
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Tuy nhin, n l c th thit lp HTTP Server theo cch m bt c khi no mt file trong mt th
mc c th c yu cu, th file khng c gi tr li; thay cho vic n c thc thi nh l
mt chng trnh v output c to t chng trnh gi ti trnh duyt hin th.
Common Gateway Interface hoc CGI l mt giao thc chun cho cc ng dng (c gi l CGI
program hoc CGI script) kh nng tng tc vi Web Server v vi Client. Nhng CGI program
ny c th c vit bng Python, PERL, Shell, C hoc C++
S cu trc CGI
Di y l s mt cu trc n gin ca CGI:
Trang 172
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
<Directory "/var/www/cgi-bin">
Options All
</Directory>
int main ()
{
Trang 173
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
HTTP Header
Dng Content-type:text/html\r\n\r\n l mt phn ca HTTP Header, m c gi ti trnh duyt.
Tt c HTTP Header c form sau:
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
Miu t
Content-type:
Trang 174
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Expires: Date
Location: URL
Last-modified: Date
Content-length: N
Set-Cookie: String
Miu t
CONTENT_TYPE
CONTENT_LENGTH
HTTP_COOKIE
HTTP_USER_AGENT
Trang 175
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
PATH_INFO
QUERY_STRING
REMOTE_ADDR
a ch IP ca host t xa to yu cu . N c th l hu ch
cho mc ch log hoc authentication
REMOTE_HOST
REQUEST_METHOD
SCRIPT_FILENAME
SCRIPT_NAME
Tn ca CGI script
SERVER_NAME
SERVER_SOFTWARE
Sau y l chng trnh CGI nh lit k tt c bin CGI. Bn click vo y xem kt qu:Get
Environment
#include <iostream>
#include <stdlib.h>
using namespace std;
Trang 176
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
Trang 177
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Phng thc GET l phng thc mc nh truyn thng tin t trnh duyt ti Web Server v
n to ra mt chui di xut hin trong Location:box ca trnh duyt. ng bao gi s dng
phng thc GET nn bn c mt khu hoc thng tin nhy cm khc truyn ti Server.
Phng thc GET c gii hn kch c v bn c th truyn 1024 k t trong mt Request String.
Trang 178
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Khi s dng phng thc GET, thng tin c truyn bi trng HTTP Header l
QUERY_STRING v s l c th truy cp trong CGI Program thng qua bin mi trng
QUERY_STRING.
Bn c th truyn thng tin bng vic ni chui cc cp key/value cng vi bt k URL hoc bn c
th s dng cc th HTML <FORM> truyn thng tin bi s dng phng thc GET.
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
Trang 179
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
form_iterator fi = formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "First name: " << **fi << endl;
}else{
cout << "No text entered for first name" << endl;
}
cout << "<br/>\n";
fi = formData.getElement("last_name");
if( !fi->isEmpty() &&fi != (*formData).end()) {
cout << "Last name: " << **fi << endl;
}else{
cout << "No text entered for last name" << endl;
}
cout << "<br/>\n";
return 0;
}
Trang 180
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
<br />
y l output thc s ca form trn. Bn c th nhp First v Last Name v sau click nt
Submit xem kt qu:
First Name:
Last Name:
Submit
Trang 181
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
y l output thc s ca form trn. Bn nhp First v Last Name v sau nhn nt Submit
xem kt qu:
First Name:
Submit
Last Name:
Maths
Physics
Select Subject
Trang 182
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
bool maths_flag, physics_flag;
maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
cout << "Maths Flag: ON " << endl;
}else{
cout << "Maths Flag: OFF " << endl;
}
cout << "<br/>\n";
physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
Trang 183
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Maths
Physics
Select Subject
Trang 184
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
form_iterator fi = formData.getElement("subject");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Radio box selected: " << **fi << endl;
}
return 0;
}
Trang 185
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
y l kt qu ca form trn:
Submit
Chng trnh C++ sau s to cpp_textarea.cgi x l input c cung cp bi trnh duyt web
thng qua text area:
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
Trang 186
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
Cgicc formData;
form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Text Content: " << **fi << endl;
}else{
cout << "No text entered" << endl;
}
return 0;
}
Trang 187
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
method="post" target="_blank">
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
<input type="submit" value="Submit"/>
</form>
Submit
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc formData;
Trang 188
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
form_iterator fi = formData.getElement("dropdown");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Value Selected: " << **fi << endl;
}
return 0;
}
Cch n lm vic
Server ca bn gi mt s d liu ti trnh duyt khch truy cp trong form ca mt Cookie. Trnh
duyt c th chp nhn Cookie ny. Nu n chp nhn, n c lu gi dng mt bn ghi thun
vn bn trn Hard drive ca khch truy cp. By gi, khi khc truy cp ti trang khc trn site ca
bn, Cookie ny l c sn thu hi. Khi c thu hi, Server ca bn bit/nh nhng g c lu
gi:
Cookie l mt bn ghi d liu thun vn bn ca 5 trng bin:
Trang 189
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Thit lp Cookie
Rt d dng gi Cookie ti trnh duyt. Nhng Cookie ny c gi cng vi HTTP Header
trc trng Content-type. Gi s bn mun thit lp UserID v Password dng Cookie. Th
thit lp Cookie s c thc hin nh sau:
#include <iostream>
using namespace std;
int main ()
{
Trang 190
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
T v d ny, bn phi hiu cch thit lp Cookie. Chng ta s dng HTTP Header l SetCookie thit lp cc Cookie.
y, n l ty thit lp cc thuc tnh ca Cookie nh Expires, Domain, v Path. Bn nh
rng, Cookie c thit lp trc khi gi dng sau: "Content-type:text/html\r\n\r\n.
Bin dch chng trnh trn to setcookies.cgi. N s thit lp 4 Cookie ti my tnh ca bn.
Thu hi Cookie
Vic thu hi tt c Cookie thit lp l kh d dng. Cookie c lu gi trong bin mi trng
CGI l HTTP_COOKIE v chng s c form sau:
key1=value1;key2=value2;key3=value3....
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
Trang 191
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
int main ()
{
Cgicc cgi;
const_cookie_iterator cci;
Trang 192
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
By gi, bin dch chng trnh trn to getcookies.cgi, v th ly danh sch tt c Cookie c
sn ti my tnh ca bn.
N s cho mt danh sch gm 4 Cookie c thit lp phn trc v tt c Cookie khc
c thit lp ti my tnh ca bn:
UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl
V d v File Upload
ti mt file ln, HTML code phi c thuc tnh enctype c thit lp l multipart/form-data.
Th input vi kiu file ny s to mt nt Browse.
<html>
<body>
<form enctype="multipart/form-data"
action="/cgi-bin/cpp_uploadfile.cgi"
method="post">
<p>File: <input type="file" name="userfile" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
Ghi ch: V d trn b v hiu ha trnh ngi dng Upload file ln Server ca chng ti.
Nhng bn c th th code trn vi Server ca bn.
Trang 193
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
int main ()
{
Cgicc cgi;
Trang 194
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
file->writeToStream(cout);
}
cout << "<File uploaded successfully>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Miu t
Containers
Algorithms
Iterators
Trang 195
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
Chng ta s cp v 3 thnh phn ca STL trong C++ trong chng tip theo khi bn lun v
Th vin chun C++ (C++ Standard Library). By gi, bn ghi nh rng, 3 thnh phn ny c mt
tp hp cc hm c nh ngha trc, m gip chng ta trong vic thc hin cc tc v phc tp
tr nn n gin hn.
Xt v d sau minh ha vector containers (l mt Template chun trong C++), m ging nh mt
mng vi mt exception m t ng x l cc nhu cu v storage ca ring n khi n cn:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// create a vector to store int
vector<int> vec;
int i;
Trang 196
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
return 0;
}
Trang 197
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
I/O
X l chui v k t
Ton hc
Date, Time v v tr
Cp pht ng
Hn hp
Cc hm cho wide-character
Trang 198
http://vietjack.com/cplusplus/index.jsp
Lp String
Lp thuc s
Lp STL Container
Lp STL Algorithm
STL Iterator
STL Allocator
Th vin Localization
Cc lp Exception Handling
Th vin h tr hm hn hp
Copyright vietjack.com
Link hu ch v C++
Free Country Cung cp source code v C++ min ph v th vin C++ cho mt s
chng trnh nh lp trnh game, th vin Template chun v lp trnh GUI.
Trang 199
http://vietjack.com/cplusplus/index.jsp
Copyright vietjack.com
C and C++ Users Group Cung cp source code t cc d n v C++ trong cc lnh vc
lp trnh a dng: AI, Animation, Compiler, Database, Debugging, Encryption, Game,
Graphics, GUI,
Trang 200