Académique Documents
Professionnel Documents
Culture Documents
PANEPISTHMIO AJHNWN
TMHMA PLHROFORIKHS
KAI THLEPIKOINWNIWN
SHMEIWSEIS
ANTIKEIMENOSTRAFOUS
PROGRAMMATISMOU
IZAMPW KARALH
AJHNA 2005
1
• ParadeÐgmata stoiqeÐwn:
– stoiqeÐo diadikasi¸n epexergasÐac proswpikoÔ
– stoiqeÐo diadikasi¸n epexergasÐac eggrfwn
– Gl¸ssec: Modula -2, Modula -3 k.a.
• ParadeÐgmata klsewn:
Idiìthtec
• StoiqeiopoÐhsh (“diaÐrei kai basÐleue”)
• Egklwbismìc (apìkruyh plhroforÐac)
• EpanaqrhsimopoÐhsh (reusability)
• Polumorfismìc
– genikeumènoi tÔpoi (stack of(X))
– genikeumènec diadikasÐec (lenghth of list of(X))
– uperfìrtwsh sumbìlwn (Arijmìc + Arijmìc, LÐsta +
LÐsta) (overloading)
8
Genikeumènoi TÔpoi
Pardeigma: StoÐbec kai Ourèc
• StoÐbec: apì ta pita èwc tic kl seic sunart sewn
• Ourèc: apì touc anjr¸pouc èwc tic diergasÐec
Apìkruyh PlhroforÐac
Pardeigma: 'Estw ìti oi genikèc ontìthtec tou probl matoc
eÐnai:
1. “pod lato”
2. “podhlthc”
'Estw ìti uprqei mia leitourgÐa gia to “pod lato” pou eÐnai
“allag taqÔthtac” pou pragmatopoieÐtai apì th leitourgÐa
tou “pod latou” “allag granazioÔ”. Th deÔterh aut
leitourgÐa thn kratme kruf (thn egklwbÐzoume): den prèpei
na mporeÐ na thn prospelaÔnei mesa o “podhlthc”.
9
C++ Genik
• C++ (=increment of C)
• Sqedisthke na
– eÐnai mia kalÔterh C
– uposthrÐzei afaÐresh dedomènwn
– uposthrÐzei antikeimenostraf programmatismì
• Bjarne Stroustrup, 1980, Bell Labs
• “C me klseic”−→ C++ to 1983
• Gia megalÔtera progrmmata
• OO qarakthristik empneusmèna apì th Simula67 (C++
=? C + Simula67)
• Embèleia (scope) onomtwn-nohmtwn
• Klseic, antikeÐmena, klhronomikìthta, filikèc klseic,
ideatèc klseic . . .
11
main()
{
..............
...............
-o file
Place output in file file.
13
#include <iostream.h>
#include "p1.h"
main()
{
cout << "hello !"<< endl;
f(5);
}
p1.cpp
#include <iostream.h>
void f(int i)
{
cout << i << endl;
}
p1.h
void f(int);
14
Onìmata
• gia tic metablhtèc
• gia tic sunart seic
• gia touc tÔpouc
• ...
• Kje ìnoma protoÔ na qrhsimopoihjeÐ prèpei na èqei
dhlwjeÐ. Se èna prìgramma prèpei, gia kje ìnoma na
èqoume ènan akrib¸c orismì (ektìc an to ìnoma anafèretai
se ontìthtec diaforetikoÔ eÐdouc, p.q. na
qrhsimopoi soume to Ðdio ìnoma gia ènan tÔpo kai mia
metablht , epitrèpetai apì th gl¸ssa rht, p.q.
uperfìrtwsh onomtwn sunart sewn)
15
ParadeÐgmata
char ch; <---- DEFINITION
int count = 1;
Embèleia (scope)
• Mia d lwsh eisgei kpoio ìnoma mèsa se mia embèleia
• H embèleia enìc onìmatoc xekin apì th d lwsh tou
onìmatoc
• Metablhtèc:
– kajolikèc (global) (pantoÔ)
– statikèc exwterikèc (èwc to tèloc tou arqeÐou)
– statikèc topikèc se sunrthsh (èwc to tèloc thc
ektèleshc thc sunrthshc)
– topikèc se sunrthsh
– topikèc se block
• Q¸roi onomtwn (namespaces)
• Klseic k.a.
• Telest c :: (scope resolution operator): gia epÐlush
embèleiac
19
extern int x;
void f();
main()
{
cout << x << endl;
f();
}
//File: f1.cpp
#include <iostream.h>
int x = 10000;
void f()
{
int x;
x = 1;
{ int x;
x = 2;
}
cout << x << endl; // prints outter x = 1
}
20
// File: f2.cpp
#include <iostream.h>
int x = 20000;
void f()
{
int x = 2;
// File: f3.cpp
#include <iostream.h>
int x = 300000;
void f()
{
int y = x; // assigns global x
// File: main.cpp
#include <iostream.h>
extern int x;
int f();
main()
{
cout << " x = "
<< x << endl;
// File: f1.cpp
int x = 10000;
int f()
{
int x = ::x;
return x++;
}
22
// File: f2.cpp
int x = 10000;
int f()
{
return x++;
// File: f3.cpp
static int x = 10000; // CAREFUL: x static to current file!
int f()
{
int x = ::x;
return x++;
}
23
double ee = E;
namespace Example{
const double PI = 3.14159;
const double E = 2.71828;
int myInt = 8;
void printValues();
}
main()
{
cout << "The namespace myInt: " << Example::myInt << endl ;
Example::printValues();
cout << "The namespace E from main: " << E << endl ;
void Example::printValues()
{
cout << "Printing from printValues" << endl;
}
26
}
}
main()
{
cout << myInt << endl;
cout << "The namespace myInt: " << myInt << endl ;
printValues();
}
27
main()
{ std::cout << "Printing!\n";}
H alli¸c:
#include <iostream>
using namespace std;
main()
{cout << "Printing!\n";}
• ShmeÐwsh: tìso stic shmei¸seic ìso kai sto mjhma qrhsimopoieÐtai tìso h pali
prosèggish gia ta arqeÐa-epikefalÐdec (me thn katlhxh .h kai qwrÐc to std) ìso
TÔpoi
• TÔpoc boolean (bool) - timèc: true, false -
• TÔpoi qarakt rwn (p.q. char)
• TÔpoi akeraÐwn (p.q. int)
• TÔpoi pragmatik¸n (p.q. double)
• TÔpoi aparÐjmhshc (p.q. enum)
• apousÐa plhroforÐac : void
• TÔpoi deikt¸n (p.q. int* )
• Arrays (p.q. char[])
• TÔpoi anafor¸n (p.q. int& )
• Domèc dedomènwn kai klseic
int main() {
char c;
unsigned char cu;
int i;
unsigned int iu;
short int is;
short iis; // Same as short int
unsigned short int isu;
unsigned short iisu;
long int il;
long iil; // Same as long int
unsigned long int ilu;
unsigned long iilu;
float f;
double d;
long double ld;
cout
<< "\n char= " << sizeof(c)
<< "\n unsigned char = " << sizeof(cu)
<< "\n int = " << sizeof(i)
<< "\n unsigned int = " << sizeof(iu)
<< "\n short = " << sizeof(is)
<< "\n unsigned short = " << sizeof(isu)
<< "\n long = " << sizeof(il)
<< "\n unsigned long = " << sizeof(ilu)
<< "\n float = " << sizeof(f)
<< "\n double = " << sizeof(d)
<< "\n long double = " << sizeof(ld)
<< endl;
} ///:~
30
Paragìmenoi TÔpoi
• * dhl¸nei deÐkth (prefix)
• & dhl¸nei anafor (prefix)
• [] dhl¸nei array (postfix)
• () dhl¸nei sunrthsh (postfix)
• ParadeÐgmata:
int* a;
float v[10];
char* p[20];
void f(int);
Telestèc
• p.q. +, -, *, /, %, ...
• EÐnai ploÔsia se telestèc, ìpwc h C
• MerikoÐ èqoun kai nèa shmasÐa, p.q. <<
• Oi telestèc
+, -, *, /, %, &, |, ^, <<, >>
sumptÔssontai me ton =
p.q. a = a + 5; −→ a += 5;
• Genik E1 op= E2 isodÔnamo me E1 = E1 op (E2) (me E1
na upologÐzetai mia for)
• Genik oi telestèc “omadopoioÔntai” apì arister ektìc
apì touc monadiaÐouc telestèc kai touc telestèc anjeshc
pou omadopoioÔntai apì dexi p.q.
a = b = c ----> a = ( b = c )
a + b + c ----> ( a + b ) + c
*p++ ----> * (p++) NOT (*p)++ (Which means what? Guess!)
Merikèc Parathr seic
• Den uprqoun entolèc anjeshc kai entolèc kl shc
sunrthshc: h anjesh kai h kl sh sunrthshc upgontai
sthn kathgorÐa twn ekfrsewn.
• Oi logikoÐ telestèc && kai || den apotimoÔn to deÔtero
ìrism touc ektìc an eÐnai aparaÐthto.
• 'Opou gÐnontai èlegqoi tim¸n al jeiac eÐnai pio
euangnwsto na grfoume rht tic logikèc ekfrseic, me
qr sh twn logik¸n telest¸n, par na uponoeÐtai o
èlegqoc me bsh tic mh mhdenikèc timèc (mhn akoloujoÔme
thn prosèggish thc C na basizìmaste sthn mhdenik h mh
mhdenik tim thc èkfrashc).
• Prosoq stic proteraiìthtec! DeÐte to paraktw
prìgramma kai aitiologeÐste ti ektup¸nei:
#include <iostream.h>
// Inspired by an example in Eckel’ s book
main()
{
int a,b;
b=1;
cout << ((a = --b) ? b : (b = -99 ))
<< \n’ << " a is " << a
<< ’\n’ << " b is " << b << endl;
b=1;
cout << (a = --b ? b : (b = -99 ))
<< ’\n’ << " a is " << a
<< ’\n’ << " b is " << b << endl;
}
36
ENTOLES (à la C)
• Entolèc Epilog c (selection/choice):
– if ( expression ) statement
– if ( expression ) statement else statement
– switch ( expression ) statement
• Entolèc Epanlhyhc (iteration):
– while ( expression ) statement
– do statement while ( expression );
– for ( init-statement ; expression(opt) ; expression )
statement
• Entolèc Metaforc Elègqou (control):
– case constant-expression : statement
– default: statement
– break;
– continue;
– return expression(opt) ;
– goto identifier ;
• OnomasÐa Entol c: identifier : statement
37
//: C03:Menu2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// A menu using a switch statement
#include <iostream>
using namespace std;
int main() {
bool quit = false; // Flag for quitting
while(quit == false) {
cout << "Select a, b, c or q to quit: ";
char response;
cin >> response;
switch(response) {
case ’a’ : cout << "you chose ’a’" << endl;
break;
case ’b’ : cout << "you chose ’b’" << endl;
break;
case ’c’ : cout << "you chose ’c’" << endl;
break;
case ’q’ : cout << "quitting menu" << endl;
quit = true;
break;
default : cout << "Please use a,b,c or q!"
<< endl;
}
}
} ///:~
40
int main() {
int secret = 15;
int guess; // No initialization needed here
do {
cout << "guess the number: ";
cin >> guess; // Initialization happens
} while(guess != secret);
cout << "You got it!" << endl;
} ///:~
42
SUNARTHSEIS
• O trìpoc gia na “knoume kti”.
• Mia sunrthsh den mporeÐ na klhjeÐ an den èqei dhlwjeÐ.
• Mia d lwsh sunrthshc perilambnei:
– to ìnoma thc sunrthshc
– ton tÔpo thc tim c pou epistrèfei
– to pl joc kai touc tÔpouc twn orismtwn thc
– p.q.
int sum(int i, int j);
void swap(int*, int*);
main()
{
int i = 16;
main()
{
int i = 16;
print(i);
print(i,16);
print(i,8);
}
46
Sunart seic inline
• Mia sunrthsh mporeÐ na oristeÐ wc inline dÐnontac mia
sumboul sto metaglwttist , na blei ton k¸dika thc
sunrthshc stic kl seic thc sunrthshc, antÐ na
qrhsimopoi sei ton klasikì mhqanismì kl shc
sunart sewn kai epistrof c apotelesmtwn. p.q.
inline int fac(int n) return (n<2?1:n*fac(n-1));
tìte, h kl sh fac(6), anloga me thn “exupnda” tou
metaglwttist , mporeÐ na gÐnei 6*5*4*3*2*1 760
6*fac(5) akìma kai na meÐnei anèpafh.
• Den eÐnai sÐgouro ìti kje inline sunrthsh ja
antimetwpisteÐ inline (p.q. amoibaÐa anadromikèc
sunart seic, sunart seic pou kaloÔn touc eautoÔc touc
anloga me thn eÐsodì touc klp.)
• H upìdeixh inline den parabizei thn klasik shmasÐa thc
kl shc sunrthshc. 'Ara, DEN EQOUME TIS
PARENERGEIES POU DHMIOURGOUNTAI APO
#define thc C.
• Oi sunart seic inline kai oi dhl¸seic const periorÐzoun
th qr sh #define sth C++.
47
main()
{
int m1, m2, i = 5, j = 10;
m2 = max2(i++,j++) ;
m1 = MAX1(i++, j++);
STAJERES
• H lèxh-kleidÐ const mporeÐ na sumperilhfjeÐ se mia
d lwsh prosdiorist (identifier) gia na ton metatrèyei se
stajer antÐ gia metablht . P.q.
const int a = 5;
+-------+
a |// 5 //|
+-------+
+------+
+--->| |
| +------+
|
|
|
+---|---+
p | |
+-------+
+-------+
+--->|/|/|/|/|
| +-------+
|
|
|
+---|---+
pc | |
+-------+
Tìte,
pc[3] = ’a’; // error
51
Tìte,
cp = "efgh"; // error
• D lwsh stajerc kai gia ta dÔo
const char *const cpc = "abcd";
+-------+
+--->|/|/|/|/|
| +-------+
|
|
|
+---|---+
cpc |///////|
+-------+
Tìte,
cpc[3] = ’a’; // error
cpc = "efgh"; // error
52
main()
{
const int a = 10;
// a = 1000; // error
// a++; // error
///////////////////////////////////////////////////////////////////
char abc[] = "abcdef";
cp[3] = ’a’; // ok
// cp = "efgh"; // error
///////////////////////////////////////////////////////////////////
const char *const cpc = abc; // constant pointer to constant
// cpc[3] = ’a’; // error
// cpc = "efgh"; // error
}
53
j = i; +-------+
j | 3 |
+-------+
+---------+ j
int i; |+-------+| |
i || 3 ||<--+
i = 3; |+-------+|
+---------+
int &j = i;
Sth deÔterh perÐptwsh, to j eÐnai “sun¸numo” tou i, mìno
pou ìtan lème i anaferìmaste sthn tim thc metablht c i
en¸ ìtan lème j anaferìmaste sto q¸ro (sthn ontìthta)
pou katalambnei h metablht j (dhlad h i).
• Oi anaforèc sumperifèrontai san stajeroÐ deÐktec proc to
antikeÐmeno me to opoÐo arqikopoioÔntai (ra pnta prèpei
na arqikopoioÔntai) kai den qreizontai dereferencing
56
main()
{
int i,j;
i=5;
j=i;
cout << j << ’\n’ << i << ’\n’;
cout << & j << ’\n’ << & i << ’\n’;
int ii;
ii = 3;
int & jj = ii;
cout << jj << ’\n’ << ii << ’\n’;
cout << & jj << ’\n’ << & ii << ’\n’;
int* p;
int* q;
p = & ii;
q = & jj;
main()
{
int i;
int &j = i;
i = 3;
int* p = &j;
cout << p << ’\n’ << &j << ’\n’ << &i << endl ;
}
59
void f(int* p) {
cout << "p = " << p << endl;
cout << "*p = " << *p << endl;
*p = 5;
cout << "p = " << p << endl;
}
int main() {
int x = 47;
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
f(&x);
cout << "x = " << x << endl;
} ///:~
60
void f(int& r) {
cout << "r = " << r << endl;
cout << "&r = " << &r << endl;
r = 5;
cout << "r = " << r << endl;
}
int main() {
int x = 47;
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
f(x); // Looks like pass-by-value,
// is actually pass by reference
cout << "x = " << x << endl;
} ///:~
61
void g()
{
int i = 5; // scope within g, automatic variable
}
void f()
{
int i = 50; // scope within f, automatic variable
static int j = 500; // scope within f, allocated in static space
g();
}
main()
{
int i = 5000; // scope within main, automatic variable
f();
}
• Pardeigma
//File: vars.cc
#include <iostream.h>
int g = 1000;
void p(int i)
{
int j = 30;
cout << "i in p is : " << i << endl;
cout << "j in p is : " << j << "\n\n\n" << endl;
}
63
void f(int i)
{
int j = 20;
static int k = 100;
p(i);
}
int main()
{
int i = 5;
cout << "i in main is :" << i << ’\n’ << endl;
f(i);
cout << "i in main is :" << i << ’\n’ << endl;
f(i++);
cout << "i in main is :" << i << ’\n’ << endl;
f(++i);
cout << "i in main is :" << i << ’\n’ << endl;
cout << "g in main is :" << g << ’\n’ << endl;
}
64
int g = 1000;
void p(int i)
{
int* j = new int(30); // now j points to heap
delete j;
}
void f(int i)
{
int j = 20;
p(i);
}
65
int main()
{
int i = 5;
cout << "i in main is :" << i << ’\n’ << endl;
f(i);
cout << "i in main is :" << i << ’\n’ << endl;
f(i++);
cout << "i in main is :" << i << ’\n’ << endl;
f(++i);
cout << "i in main is :" << i << ’\n’ << endl;
cout << "g in main is :" << g << ’\n’ << endl;
}
66
void p()
{
int k = 300;
int* kk = &k;
cout << "kk points to :" << *kk << "\n\n\n" << endl;
cout << "kk points to :" << *kk << "\n\n\n" << endl;
cout << "j after deletion points to :" << *j << "\n\n\n" << endl;
}
int main()
{
p(); p();
}
67
void remove(char*,char);
main()
{
char string1[] = "abagaadagaga";
char string2[] = "abagaadagaga";
char string3[] = "ccabbbb";
remove(string1, ’a’);
cout << string1 <<endl;
remove(string2, ’g’);
cout << string2 <<endl;
remove(string3, ’a’);
cout << string3 <<endl;
}
return length;
}
main()
{
char* string1 = "abagaadagaga";
main()
{
char* string1 = "abagaadagaga";
char res[l+1];
EÐsodoc/Exodoc Metablht¸n
'Exodoc metablht¸n : me qr sh tou telest <<
• Genik morf : <ReÔmaExìdou> << <Metablht >
• P.q.
int i = 10;
cout << i;
EÐsodoc metablht¸n : me qr sh tou telest >>
• Genik morf : <ReÔmaEisìdou> >> <Metablht >
• P.q.
float f ;
cin >> f;
• Sthn èkfrash eisìdou exìdou, de dÐnetai kami
plhroforÐa gia ton tÔpo thc metablht c. To epijumhtì
apotèlesma epitugqnetai lìgw twn uperfortwmènwn
orism¸n twn telest¸n << kai >>.
• Dedomènou ìti oi telestèc << kai >> epistrèfoun reÔma
exìdou kai reÔma eisìdou, antÐstoiqa, mporoÔme na touc
qrhsimopoi soume perissìterec apì mia for se mia
èkfrash.
81
ParadeÐgmata
#include <iostream.h>
main()
{
int i;
cin >> i;
float f;
cin >> f;
char c;
cin >> c;
char buf[10];
cin >> buf;
main()
{
int i;
float f;
char c;
char buf[10];
Diamorfwtèc (manipulators)
• Gia na grfoume sthn Ðdia gramm eisìdou exìdou tic
leitourgÐec pou jèloume na gÐnoun.
• Orismìc sunart sewn pou lègontai diamorfwtèc kai
mporoÔn na perilhfjoÔn stic ekfrseic I/O.
• Genik morf :
ostream& < manip name >(ostream& < stream >)
istream& < manip name >(istream& < stream >)
ostream& < manip name >(ostream& < stream >,
< type param >)
...
• MporoÔn na oristoÔn kai apì to qr sth (lìgw
upost rixhc uperfìrtwshc)
84
Enswmatwmènoi Diamorfwtèc
dec: input/output data in decimal (input/output)
hex: input/output data in hexadecimal (input/output)
oct: input/output data in octal (input/output)
endl: output nl and flush the stream (output)
ends: output nl (output)
flush: flush the stream (output)
ws: skip leading whitespace (input)
resetiosflags(long f): turn off flags specified in "f"
(input/output)
setbase(int base): set the number base to "base" (output)
setfill(int ch): set fill character to "ch" (output)
setiosflags(long f): turn on the flags specified in "f"
(input/output)
setprecision(int p): set the number of digits of precision
(output)
setw(int w): set the field width to "w" (output)
...
Parathr seic:
• Gia touc diamorfwtèc pou den èqoun orÐsmata den prèpei na
bzoume parenjèseic.
• Gia na qrhsimopoi soume touc diamorfwtèc pou èqoun
orÐsmata prèpei na perilboume to arqeÐo -epikefalÐda
<iomanip.h> (<iomanip>).
85
Anoigma/KleÐsimo arqeÐwn
• AnoÐgoume èna arqeÐo sundèontc to me èna reÔma.
• Ta reÔmata eÐnai stigmiìtupa twn klsewn ifstream,
ofstream, fstream.
• void open(const char* filename, int mode, int
access=filebuf::openprot), ìpou
– filename: to ìnoma tou arqeÐou pou anoÐgoume
– mode: mia apì tic ios::app, ios::ate, ios::binary,
– ios::in, ios::nocreate, ios::noreplace, ios::out,
ios::trunc (mporoÔn na sunduastoÔn me OR)
– access, arket qamhloÔ epipèdou, sqedìn pnta paÐrnei
th default tim
88
ParadeÐgmata:
• 'Exodoc metablht¸n se arqeÐo
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream out("test");
if (!out) {
cout << "Cannot open file.\n";
return 1;
}
out.close();
return 0;
}
• EÐsodoc metablht¸n apì arqeÐo
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch; int i; float f; char str[80];
ifstream in("test");
if(!in) {
cout << "Cannot open file.\n";
return 1;
}
in >> i >> f >> ch >> str;
cout << i << " " << f << " " << ch << endl;
cout << str << endl;
in.close();
return 0;
}
90
char ch;
while (from.get(ch)) to.put(ch); // copy characters
EÐsodoc Metablht¸n
Kat’ analogÐa me thn èxodo.
Sthn klsh istream orÐzetai o telest c >> gia na qeirÐzetai
thn eÐsodo twn enswmatwmènwn tÔpwn thc C++.
class istream : public virtual ios
{
// ...
public:
basic_istream& operator>>(const char*);
basic_istream& operator>>(char&);
basic_istream& operator>>(short&);
basic_istream& operator>>(int&);
// ...
};
KLASEIS
• Orismìc apì to qr sth nèwn tÔpwn, h prìsbash sta
stoiqeÐa twn opoÐwn gÐnetai mèsw sugkekrimènwn
sunart sewn.
• 'Enac tÔpoc eÐnai h fusik anaparstash miac ideat c
ontìthtac. p.q. o tÔpoc float me +,-,* . . . eÐnai h
anaparstash tou pragmatikoÔ arijmoÔ twn majhmatik¸n.
• 'Ena prìgramma pou qrhsimopoieÐ tÔpouc pou
prosomoi¸noun tic ontìthtec thc efarmog c gÐnetai
eukolìtera katanohtì.
• Diaqwrismìc twn leptomerei¸n ulopoÐhshc tou tÔpou apì
tic idiìthtec/leitourgÐec tou tÔpou pou eÐnai aparaÐthtec
gia th swst qr sh tou.
98
struct date {
int day, month, year;
void set(int, int, int);
void get(int&, int&, int&);
};
main()
{
date today;
int d,m,y;
today.set(3,5,2004);
today.get(d,m,y);
cout << "day " << d
<< ", month " << m
<< ", year " << y << endl ;
}
public:
<dhl¸seic>
};
'H alli¸c:
class< ìnoma klshc >
{
public:
<dhl¸seic>
private:
<dhl¸seic>
};
103
class date {
private:
int day, month, year; // data members kept hidden
public:
void set(int, int, int);
void get(int&, int&, int&);
};
main()
{
date today;
int d,m,y;
today.set(3,5,2004);
today.get(d,m,y);
cout << "day " << d
<< ", month " << m
<< ", year " << y << endl ;
}
s.set_name("FName LName");
s.set_no(555);
s.set_year_of_studies(1);
year = s.get_year_of_studies();
no = s.get_no();
}
106
ArqeÐa:
• Orismìc nèou tÔpou:
– student.h: orismìc tou nèou tÔpou (arqeÐo
-epikefalÐda)
– student.cpp: orismìc twn sunart sewn -mel¸n tou
nèou tÔpou (arqeÐo k¸dika)
//File: student.h
class Student {
private:
char* name;
int no;
int year_of_studies;
public:
void set_name(const char*);
void set_no(int);
void set_year_of_studies(int);
char* get_name();
int get_no();
int get_year_of_studies();
};
//File: student.cpp
#include <string.h>
#include <iostream.h>
#include "student.h"
char* Student::get_name(){
return name;
}
int Student::get_no(){
return no;
}
int Student::get_year_of_studies(){
return year_of_studies;
}
int main()
{
Student s;
int year, no;
s.set_name("First Last");
s.set_no(100);
s.set_year_of_studies(1);
s.set_name("NFirst Last");
year = s.get_year_of_studies();
no = s.get_no();
cout << "\nYear of studies is " << year <<
" for student with no " << no <<
" and name " << s.get_name() << endl ;
}
108
O deÐkthc this
ArqikopoÐhsh stigmiotÔpwn
• DÐnetai h dunatìthta ston programmatist na dhl¸nei
kpoia(ec) sunart seic pou èqoun san stìqo na
dhmiourgoÔn kai na arqikopoioÔn antikeÐmena (dhlad ,
uprqei h dunatìthta tautìqronhc arqikopoÐhshc kat th
stigm thc d lwshc).
• Oi sunart seic autèc lègontai sunart seic kataskeu c
(constructors) kai prosdiorÐzontai apì to ìti èqoun to Ðdio
ìnoma me thn klsh. p.q.
class date{
// ...
public:
date(int, int, int);
date(int, int); // this year
date(int); // this year and this month
date(); // today
// ...
};
main()
{
// ...
date day(14);
date day_month(14,3);
date today;
// ...
}
Katastrof stigmiotÔpwn
• H antÐstrofh diadikasÐa thc kataskeu c antikeimènwn eÐnai
ekeÐnh thc katastrof c antikeimènwn.
• PolloÐ tÔpoi qreizontai na oristeÐ mia sunrthsh
katastrof c (destructor) antikeimènwn gia na diasfalisteÐ
h orj apeleujèrwsh tou q¸rou pou katalambnei èna
antikeÐmenì touc.
• Genik morf , gia mia klsh X , ~X() (~: sumpl rwma)
• 'Otan ta antikeÐmena dhmiourgoÔntai mèsw new, dunamik,
qreizetai sunrthsh katastrof c pou na kaleÐtai kai na
apeleujer¸nei to q¸ro pou katèlaban.
• 'Otan èna antikeÐmeno bgaÐnei apì thn embèleia, kaleÐtai h
sunrthsh katastrof c thc klshc tou. PROSOQH: sth
C++, bgaÐnontac apì to s¸ma thc main, den stamat h
ektèlesh: kaloÔntai kai oi sunart seic katastrof c ìlwn
twn antikeimènwn pou dhmiourg jhkan.
113
//////////////////////////////////////////////////////////
void Student::set_no(int n)
{no = n;}
void Student::set_year_of_studies(int y)
{year_of_studies = y;}
//////////////////////////////////////////////////////////
char* Student::get_name()
{return name;}
int Student::get_no()
{return no;}
int Student::get_year_of_studies()
{return year_of_studies;}
//////////////////////////////////////////////////////////
Student::~Student()
{
cout << "Deleting student with name " << name << endl ;
delete[] name;
}
//////////////////////////////////////////////////////////
Student::Student(const Student& s)
{
// name = s.name; Careful: this is the result
// of default copy
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just created a student by copying ... " << endl;
}
//////////////////////////////////////////////////////////
}
116
void bla(Student s)
{ cout << "Body of the bla function" << endl;}
Student blaS(Student s)
{ cout << "Body of the blaS function" << endl;
return s;}
int main()
{
Student s("First Last");
cout << "This is the first output of the main function "
<< endl;
s.set_no(100);
s.set_year_of_studies(1);
s.set_name("NFirst Last");
year = s.get_year_of_studies();
no = s.get_no();
cout << "\nYear of studies is " << year <<
" for student with no " << no <<
" and name " << s.get_name() << endl ;
///////////////////////////////////////////////////////////////////////
// Student scopied(s); // Student creation with copy constructor
// Student sassgncopied = s; // Student creation EQUIVALENT TO
// // THE ABOVE
// scopied = sassgncopied; // Student assignment (to an existent
// // Student)
// bla(s);
//
// scopied = blaS(s);
//File: refclass_test.cpp
#include <iostream.h>
#include "student_constr.h"
void bla(Student& s)
{
cout << "Body of the bla function" << endl;
}
int main()
{
Student s("First Last");
Student & rs = s;
cout << "This is the first output of the main function "
<< endl;
int year, no;
s.set_no(100);
s.set_year_of_studies(1);
s.set_name("NFirst Last");
year = s.get_year_of_studies();
no = s.get_no();
cout << "\nYear of studies is " << year <<
" for student with no " << no <<
" and name " << s.get_name() << endl ;
118
/////////////////////////////////////////////////////////////////////////////
Student scopied(s);
//
//
bla(s);
//
scopied = blaS(s);
public:
Time() { hours = 0; mins = 0; };
~Time() {};
void set(int,int);
void print();
Time add(Time);
};
//File: time1.cc
#include <iostream.h>
#include "time1.h"
void Time::print()
{
cout << hours <<" hours and "
<< mins <<" mins " << endl;
}
print();
Time Time::add(Time t)
{
Time result;
result.hours = 0;
result.mins = mins + t.mins;
return result;
}
int tmins;
public:
void set(int,int);
void print();
Time add(Time);
};
//File: time2.cc
#include <iostream.h>
#include "time2.h"
void Time::print()
{
cout << tmins / 60 <<" hours and "
<< tmins \% 60 <<" mins " << endl;
}
121
print();
// this->print();
}
Time Time::add(Time t)
{
Time result;
result.tmins = tmins + t.tmins;
return result;
}
122
int main()
{
Time t;
t.print();
t.set(2,59);
Time tt;
tt.set(1,59);
Time ttt;
ttt = t.add(tt);
ttt.print();
return 0;
}
int main()
{
Flight AthensParis;
AthensParis.FNo = 314;
AthensParis.DCity = "Athens";
AthensParis.ACity = "Paris";
AthensParis.DTime.set(10,30);
AthensParis.Duration.set(3,15);
Time ATime;
ATime = AthensParis.DTime.add(AthensParis.Duration);
return 0;
}
124
EPANAQRHSIMOPOIHSH (reusability)
• mèsw sÔnjeshc (composition) has a
• mèsw klhronomikìthtac (inheritance) is a
125
SÔnjesh
• Mia klsh èqei san mèlh antikeÐmena llhc klshc.
• DhmiourgÐa antikeimènwn: Pr¸ta dhmiourgoÔntai ta
antikeÐmena pou eÐnai mèlh thc klshc (me th seir pou
dhl¸nontai ston orismì thc klshc ki ìqi me th seir pou
emfanÐzontai sth sunrthsh kataskeu c thc klshc) ki
èpeita dhmiourgeÐtai to antikeÐmeno thc klshc.
• Katastrof antikeimènwn: AkoloujeÐtai h antÐstrofh
seir apì ekeÐnh thc dhmiourgÐac, dhlad , pr¸ta ekteleÐtai
to s¸ma thc sunrthshc katastrof c thc klshc kai met
ekeÐnec twn mel¸n thc (me thn antÐstrofh seir thc
d lwshc).
126
Pardeigma gia:
• ton orismì pollapl¸n sunart sewn kataskeu c (me qr sh
default tim¸n sta orÐsmata)
• th qr sh initializer list gia non -class mèlh -dedomèna
(isodÔnamo me anjesh sto s¸ma thc sunrthshc
kataskeu c) (ShmeÐwsh: aut h suntaktik dunatìthta
parèqetai gia lìgouc sumbatìthtac me ta class mèlh
-dedomèna ìpou sthn perÐptwsh aut , ètsi pernme
paramètrouc stic sunart seic kataskeu c touc)
• ton orismì klshc me mèlh -dedomèna pou an koun se llec
klseic
• thn kl sh (non -trivial synthesized) sunart sewn
kataskeu c/katastrof c gia ta antikeÐmena thc sÔnjethc
klshc
PeiramatisteÐte bgzontac ta sqìlia twn orism¸n twn
metablht¸n sto s¸ma thc main tou akìloujou progrmmatoc.
127
#include <iostream.h>
/////////////////////////////////////////////////////////////////////
class Date {
int day;
int month;
int year;
public:
Date(int d = 1, int m = 1, int y = 2004)
// : day(d), month(m), year(y) // non-class types,
// i.e. intitializer list
// alternative to assignment
// in the body
{
day = d; month = m; year = y;
~Date()
{
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl;
}
void print()
{
cout << day << ’ ’ << month << ’ ’ << year
<< endl;
}
};
/////////////////////////////////////////////////////////////////////
class Time {
int hours;
int mins;
public:
Time(int h = 0, int m = 0 )
// : hours(h); mins(m)
128
{
hours = h; mins = m;
cout << "I just created a Time with value: "
<< hours << ’ ’ << mins << endl;
}
~Time()
{ cout << ’\n’ << "I am destroying a Time with value: "
<< hours << ’ ’ << mins << endl; }
void print() {
cout << hours <<" hours and "<< mins <<" mins "
<< endl;}
};
/////////////////////////////////////////////////////////////////////
class DetailedDate{
Date date;
Time time;
public:
DetailedDate()
// Default constructor is synthesized, using the default constructors
// of the data members.
{ cout << "DetailedDate was just created with value:"
<< ’\n’ << endl;
// NO VISIBILITY in private part
// cout << date.day << ’ ’ << date.month << ’ ’
// << date.year << endl;
// cout << time.hours <<" hours and "<< time.mins
// <<" mins " << endl;
date.print();
time.print();
}
date.print();
129
time.print();
}
~DetailedDate()
{
cout << ’\n’
<< "I am destroying a DetailedDate with value: "
<< endl;
date.print();
time.print();
}
};
/////////////////////////////////////////////////////////////////////
int main()
{
// Date d1;
// Date d2(3);
// Date d3(3,4);
// Date d4(3,4,2005);
// Time t1;
// Time t2(35);
// Time t3(2,35);
DetailedDate dd1;
// DetailedDate dd2(25,10,2005,3,45);
return 0;
}
130
int day;
int month;
int year;
public:
Date(int d = 1, int m = 1, int y = 2004)
{
day = d; month = m; year = y;
~Date() {
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl; }
void print() {
cout << day << ’ ’ << month << ’ ’ << year << endl;}
};
/////////////////////////////////////////////////////////////////////
class Time {
int hours;
int mins;
public:
Time(int h = 0, int m = 0 )
{
hours = h; mins = m;
cout << "I just created a Time with value: "
131
~Time() {
cout << ’\n’ << "I am destroying a Time with value: "
<< hours << ’ ’ << mins << endl; }
void print() {
cout << hours <<" hours and "<< mins <<" mins "
<< endl;}
};
/////////////////////////////////////////////////////////////////////
class DetailedDate{
Date* date;
Time* time;
public:
DetailedDate()
{ cout << "DetailedDate was just created with value:"
<< ’\n’ << endl;
// CAREFUL: no space has been allocated or intialized
// for Date and Time
this->date->print(); // error
this->time->print(); // error
}
~DetailedDate()
{
cout << ’\n’
<< "I am destroying a DetailedDate with value: "
<< endl;
date->print();
time->print();
}
};
/////////////////////////////////////////////////////////////////////
int main()
{
DetailedDate dd1;
return 0;
}
132
int day;
int month;
int year;
public:
Date(int d = 1, int m = 1, int y = 2004)
{
day = d; month = m; year = y;
~Date() {
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl;
}
void print() {
cout << day << ’ ’ << month << ’ ’ << year << endl;}
};
/////////////////////////////////////////////////////////////////////
class Time {
int hours;
int mins;
public:
Time(int h = 0, int m = 0 )
{
hours = h; mins = m;
cout << "I just created a Time with value: "
<< hours << ’ ’ << mins << endl;}
133
~Time() {
cout << ’\n’ << "I am destroying a Time with value: "
<< hours << ’ ’ << mins << endl; }
void print() {
cout << hours <<" hours and "<< mins <<" mins "
<< endl;}
};
/////////////////////////////////////////////////////////////////////
class DetailedPDate{
Date* date;
Time* time;
public:
DetailedPDate()
{ cout << "DetailedPDate was just created with value:"
<< ’\n’ << endl;
date->print();
time->print();
}
134
~DetailedPDate()
{
cout << ’\n’
<< "I am destroying a DetailedPDate with value: "
<< endl;
date->print();
time->print();
delete date;
delete time;
}
};
/////////////////////////////////////////////////////////////////////
int main()
{
// DetailedPDate dd1;
// DetailedPDate dd2(25,10,2005,3,45);
return 0;
}
135
KLHRONOMIKOTHTA (inheritance)
VEHICLE:
(move(), position(), wheels())
/ | \
/ | \
/ | \
+ + +
/ | \ \
/ | \ \
+ | \ +
| \
CABRIO: | \ 4_WHEEL_DRIVE:
(no_roof()) | \ (drive_in_4_wheels())
| +
|
| LIMOUZINE:
+ (no_back_door())
HATCHBACK:
class Employee
{
public:
Employee(const char*, const char*);
void print() const;
~Employee();
private:
char* firstname;
char* lastname;
};
private:
double wage;
double hours;
};
139
main()
{
HourlyWorker hw("FN", "LN", 0.0, 100.0);
hw.print();
}
140
'Opou:
bmcs: constructors of base class data members
(me th seir pou emfanÐzontai ston orismì
thc klshc)
bc: constructor of base class
dmcs: constructors of derived class data members
(me th seir pou emfanÐzontai ston orismì
thc klshc)
dc: constructor of derived class
dd: destructor of derived class
dmds: destructors of derived class data members
(me thn antÐstrofh seir pou emfanÐzontai
ston orismì thc klshc)
bd: destructor of base class
bmds: destructors of base class data members
(me thn antÐstrofh seir pou emfanÐzontai
ston orismì thc klshc)
145
class Y : public X {
int i; // Different from X’s i
public:
Y() { i = 0; }
int change() {
i = permute(); // Different name call
return i; }
void set(int ii) {
i = ii;
X::set(ii); } // Same-name function call
};
int main() {
cout << "sizeof(X) = " << sizeof(X) << endl;
cout << "sizeof(Y) = "
<< sizeof(Y) << endl;
Y D;
D.change();
// X function interface comes through:
D.read();
D.permute();
// Redefined functions hide base versions:
D.set(12);
} ///:~
146
public :
PGStudent(const char* nam, int gy=0) : Student(nam), gyear(gy)
{ cout << "The Graduation year was :" << gyear
<< endl; }
main()
{
PGStudent pgs1("FN1");
// PGStudent pgs2("FN2",2004);
// PGStudent pgs3(pgs2); // copy constructor invoked:
// - copy constructor of Student is used
// to copy the Student subobject
// - bitwise copy for the rest
// Inherited functions:
pgs1.set_no(123);
cout << pgs1.get_no() << endl;
}
147
class Date {
int day;
int month;
int year;
public:
Date(int d = 1, int m = 1, int y = 2004)
{
day = d; month = m; year = y;
~Date() {
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl;
}
void print() {
cout << day << ’ ’ << month << ’ ’ << year << endl;}
};
/////////////////////////////////////////////////////////////////////
class PGStudent : public Student {
public :
PGStudent(const char* nam) : Student(nam) {}
148
main()
{
PGStudent pgs1("FN");
PGStudent pgs2(pgs1);
class A1 {
public:
A1() { cout << "constructing an A1" << endl; };
A1(int i) { cout << "constructing an A1 with :"
<< i << endl; };
~A1() {cout << "destroying an A1" << endl; }; };
class A2 {
public:
A2() { cout << "constructing an A2" << endl; };
A2(int i) { cout << "constructing an A2 with :"
<< i << endl; };
~A2() {cout << "destroying an A2" << endl; }; };
class B1 {
public:
B1() { cout << "constructing a B1" << endl; };
~B1() {cout << "destroying a B1" << endl; }; };
class A {
A1 a1;
A2 a2;
public:
A() { cout << "constructing an A" << endl; };
A(int i, int j) : a2(i), a1(j)
{ cout << "constructing an A" << endl; };
~A() {cout << "destroying an A" << endl; }; };
class B : public A {
B1 b1;
public:
B() { cout << "constructing a B" << endl; };
B(int i, int j) : A(i,j)
{ cout << "constructing a B" << endl; };
~B() {cout << "destroying a B" << endl; }; };
/////////////////////////////////////////////////////////////////////
150
void bloo(B* b)
{ cout << "Printing in bloo" << endl; }
void bla(B b)
{ cout << "Printing in bla" << endl;
bloo(&b); }
////////////////////////////////////////////////////////////////////
main()
{
B object1;
B object2(5,15);
cout << "First printing in main " << endl;
bla(object1);
bloo(&object2);
class A {};
main()
{
A a;
cout << sizeof(a) << endl;
A b;
cout << &a << ’\n’ << &b << endl; // different addresses
}
151
int gyear;
char* first_degree; // We also include the
// first degree of PGStudent
public :
PGStudent(const char* nam, const char* fd, int gy=0)
: Student(nam), gyear(gy)
{
first_degree = new char[strlen(fd)+1];
strcpy(first_degree,fd);
cout << "I just constructed a PGstudent " << endl; }
~PGStudent()
{
cout << "Deleting postgraduate student with name "
<< get_name() << endl ;
delete[] first_degree;
}
main()
{
PGStudent pgs("FN1","FDEGR");
153
//////////////////////////////////////////////////////
// VARIOUS:
//////////////////////////////////////////////////////
// Pointer to Student:
// Student* ps = new Student("TheNew");
// delete ps; // otherwise the destructor of Student is not called
// Array of Student:
// Student ss[100]; // Problem: no default constructor is
// provided for Student
// Student* pss = new Student[100]; // Same as above
///////////////////////////////////////////////////////
Student s("FirstLast");
Student* ps;
PGStudent* ppgs;
// pgs = s; // error
// s = pgs; // Student redefinition of operator = is called
class Instrument {
public:
void play(note) const {
cout << "Instrument::play" << endl;
}
};
// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument {
public:
// Redefine interface function:
void play(note) const {
cout << "Wind::play" << endl;
}
};
void tune(Instrument& i) {
// ...
i.play(middleC);
}
int main() {
Wind flute;
tune(flute); // Upcasting
} ///:~
157
class Instrument {
public:
virtual void play(note) const {
cout << "Instrument::play" << endl;
}
};
// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument {
public:
// Override interface function:
void play(note) const {
cout << "Wind::play" << endl;
}
};
void tune(Instrument& i) {
// ...
i.play(middleC);
}
int main() {
Wind flute;
tune(flute); // Upcasting
} ///:~
158
public :
PGStudent(const char* nam, const char* fd, int gy=0)
: Student(nam), gyear(gy)
{
first_degree = new char[strlen(fd)+1];
strcpy(first_degree,fd);
cout << "I just constructed a PGstudent " << endl; }
~PGStudent()
{ cout << "Deleting postgraduate student with name "
<< get_name() << endl ;
delete[] first_degree;
}
main()
{
PGStudent pgs1("FN1","FDEGR");
// Inherited functions:
pgs1.set_no(123);
cout << pgs1.get_no() << endl;
}
159
class Student {
private:
char* name;
int no;
int year_of_studies;
public:
Student(const char*);
Student(const Student&);
// ~Student();
virtual ~Student();
char* get_name();
int get_no();
int get_year_of_studies();
// void print();
virtual void print();
};
student constr.cc:
#include <string.h>
#include <iostream.h>
#include "student_constr.h"
void Student::print()
{
cout << "Student’s name is: " << name << endl;
}
160
//////////////////////////////////////////////////////////
void Student::set_name(const char* nam)
{
delete[] name;
name = new char[strlen(nam)+1];
strcpy(name,nam);
}
void Student::set_no(int n)
{
no = n;
}
void Student::set_year_of_studies(int y)
{
year_of_studies = y;
}
//////////////////////////////////////////////////////////
char* Student::get_name()
{
return name;
}
int Student::get_no()
{
return no;
}
int Student::get_year_of_studies()
{
return year_of_studies;
}
//////////////////////////////////////////////////////////
Student::~Student()
{
cout << "Deleting student with name " << name
<< endl ;
delete[] name;
}
//////////////////////////////////////////////////////////
Student::Student(const char* nam)
{
name = new char[strlen(nam)+1];
strcpy(name,nam);
161
Student::Student(const Student& s)
{
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just created a student by copying ... "
<< endl;
}
//////////////////////////////////////////////////////////
Student& Student::operator=(const Student& s)
{
if (this != &s) // Careful not to assign to itself
{
delete[] name;
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just performed a student ASSIGNMENT ... "
<< endl;
}
return *this;
}
162
int gyear;
char* first_degree;
public :
~PGStudent()
{
cout << "Deleting postgraduate student with name "
<< get_name() << endl ;
delete[] first_degree;
}
void print()
{ Student::print();
cout << "First degree is: " << first_degree << endl; }
};
163
main()
{
// PGStudent pgs("FN1","FDEGR");
// Student s("FirstLast");
// s.print();
// pgs.print();
// pgs.Student::print();
/////////////////////////////////////////////
// Student* ps=&s;
// PGStudent* ppgs=&pgs;
// ps->print();
// ppgs->print();
/////////////////////////////////////////////
// Student* ss[2];
// ss[0] = &s;
// ss[1] = &pgs;
// ss[0]->print();
// ss[1]->print();
// delete ss[0];
// delete ss[1];
/////////////////////////////////////////////
// delete p1;
// delete p2; }
164
• H klsh Shape:
class Shape
{
// ...
virtual void print() const = 0;
// ...
};
166
Pollapl Klhronomikìthta
Employee Student
\ /
\ /
\ /
+ +
WorkingStudent
PROTUPA (templates)
• Sunart sewn
• Klsewn
168
Prìtupa Sunart sewn
• Genik morf :
template< class T >
• p.q. antÐ,
void printArray(const int* array, const int count);
void printArray(const double* array, const int count);
// ...
knoume
template < class T >
void printArray(const T* array, const int count)
{
for (int i=0; i < count; i++)
cout << array[i] << " ";
cout << endl;
}
Prìtupa Klsewn
• ParametrikoÐ tÔpoi.
• GenikoÐ orismoÐ klsewn me sugkekrimenopoÐhsh (ìqi
exeidÐkeush) me bsh sugkekrimènouc tÔpouc.
• Sthn epikefalÐda miac klshc mporoÔn na qrhsimopoihjoÔn
kai parmetroi pou den eÐnai tÔpoi, p.q.
template<class T, int elements>
class Stack
{
// ...
}
tìte,
Stack<double,100>
private:
int size;
int top;
T* stackPtr;
// ...
-kleidioÔ const tìso sth d lwsh ìso kai ston orismì thc
sunrthshc -mèlouc (jètontc to met tic paramètrouc thc
sunrthshc).
class Time
{
public:
// ...
int getHour() const;
int getMinute() const;
int getSecond() const;
// ...
};
// ...
public:
Count() { x= 0}
void print() const { cout << x << endl; }
private:
int x;
};
int main()
{
Count counter;
counter.print();
setX(counter,8);
counter.print();
return 0;
}
178
Pardeigma:
D lwsh statik¸n mel¸n:
// employee.h
class Employee
{
public:
Employee(const char*, const char*);
~Employee();
private:
char* firstName;
char* lastName;
Employee::~Employee()
{
delete [] firstName;
delete [] lastName;
int main()
{
// Access with class scope:
cout << Employee::getCount() << endl;
delete e1;
delete e2;
return = 0;
}
182
METATROPES TUPWN
• MporeÐ na qreiasteÐ na metatrèyoume rht mia tim , pou
eÐnai kpoiou tÔpou, se kpoion llo tÔpo. p.q.
float r = float(1);
metatrèpei ton akèraio 1 ston pragmatikì 1.0f gia na
dojeÐ san tim ston pragmatikì r.
• Uprqoun dÔo trìpoi na to sumbolÐsoume:
1. (à la C): cast, me th qr sh parenjèsewn, p.q.
(double) a
2. “sunarthsiak ” graf :
double(a)
den mporeÐ ìmwc na qrhsimopoihjeÐ gia tÔpouc pou
èqoun sÔnjeto sumbolismì. p.q.
OQI char*(0777);
MONO (char*) 0777;
• Sth C++ den uprqei tìso èntonh angkh gia rht
metatrop tÔpwn, antÐjeta me th C.
• Stouc deÐktec, anjesh apì/se void* den qreizetai rht
metatrop tÔpou.
• Autìmath metatrop tÔpwn, orismènh apì ton qr sth:
– mèsw orismoÔ sunart sewn kataskeu c (tou tÔpou
-proc me ìrisma tou tÔpou -apì)
– mèsw orismoÔ telest¸n (tou tÔpou -proc pou
efarmìzontai ston tÔpo -apì)
• Rht metatrop tÔpwn (gia na agno soume teleÐwc tic
metatropèc à la C):
184
BibliografÐa
• Bjarne Stroustrup, “H Gl¸ssa ProgrammatismoÔ C++”
(TrÐth Ameriknikh 'Ekdosh), ekdìseic “Kleidrijmoc”,
1999
• Bruce Eckel, “Thinking In C++” (Second Edition),
Volume One: Introduction to Standard C++, Prentice
Hall, 2000
• ISO International Standard: Programming Languages —
C++, 1998
• Stanley B. Lippman, Josee Lajoie, “C++ Primer” (3rd
Edition), Addison-Wesley, 1998
• Stanley B. Lippman, “Inside the C++ Object Model”
Addison-Wesley, 1996
• Herbert Schildt, “C++: The Complete Reference” (2nd
Edition), McGraw-Hill, 1995
• Till Jeske, “C++ Nitty Gritty”, Addison-Wesley, 2000
(Pearson Education, 2002)
• The Standard Template Library:
http://www.sgi.com/tech/stl
• Bertrand Meyer, “Object -Oriented Software
Construction” (2nd Edition), Prentice Hall, 2000
• Russel Winder, Graham Roberts, “Developing Java
Software” (2nd Edition), John Wiley and Sons, 2000
186