C++ Notes
C++ Notes
m
k
o
d
l
a
m
a
Birim
Testler
Tmletirme
Testleri
leri Seviye
Testleri
dorulama testi,
sistem testi,
alpha ve beta testleri,...
13
C++ ve NESNEYE DAYALI PROGRAMLAMA 25
Hatann trn ve
yerini bulmak iin
geen sre
Hatay dzeltmek
iin geen sre
Hata Ayklama
Hata Ayklama Hata Ayklama
Error checking
11%
Software
interface
6%
Hardware
interface
8%
Logic
20%
Data handling
11%
User interface
12%
Specifications
25%
Standards
7%
Origin of
errors/defects
specification/requirem
ents
desig
n
code
C++ ve NESNEYE DAYALI PROGRAMLAMA 26
D. Ritchie tarafndan iki eski dilden yararlanlarak gelitirilmitir.
BCPL (Binary Coded Programming Language) ve B
UNIX iletimsistemini yazmak iin kullanlmtr.
Gnmzde bir ok iletim sistemi C veya C++ kullanlarak
yazlr.
Donanmdan bamsz, tanabilir (portable) programlar
yazlabilir.
C programlar fonksiyon (function) ad verilen bamsz
program paralarndan oluur.
Programclar kendi fonksiyonlarn yazabildikleri gibi, C
ktphanesinde bulunan ve nceden yazlm olan
fonksiyonlar da kullanabilirler.
C Programlama Dili
C Programlama Dili C Programlama Dili
14
C++ ve NESNEYE DAYALI PROGRAMLAMA 27
C Programnn Gelitirilme Aamalar
1. Edit (Kaynak kod)
2. Preprocess (n ilemci)
3. Compile (Derleme)
4. Link (Balama)
5. Load (Ykleme)
6. Execute (Yrtme)
C Program Gelitirme Ortam
C Program Gelitirme Ortam
Loader
Primary
Memory
Compiler
Editor
Preprocessor
Linker
CPU
Primary
Memory
Disk
Disk
Disk
Disk
Disk
.
.
.
.
.
.
C++ ve NESNEYE DAYALI PROGRAMLAMA 28
Aklamalar
/* ve */ simgeleri arasndaki yazlar gz ard edilir.
Program anlalr hale getirmek iin kullanlr.
#include <stdio.h>
nilemci belli bir dosyay diskten okuyup programa ekler.
<stdio.h> dosyasnda giri/k fonksiyonlarnn tanmlar bulunur.
/* lk C program */
#include <stdio.h>
void main()
{
printf( "Welcome to C!\n" );
}
Welcome to C!
15
C++ ve NESNEYE DAYALI PROGRAMLAMA 29
void main() void main()
C programlar fonksiyonlardan oluur.
lk alan fonksiyonun ad main dir.
Kvrck parantezler { { ve } } bir bloun ban ve sonunu
belirtir.
printf printf( "Welcome to C! ( "Welcome to C!\ \n" ); n" );
Bir k fonksiyonudur. Ekrana verilerin yazlmasn salar.
Bu fonksiyon nceden hazrlanmtr ve derleyicinin
ktphanesinde yer almaktadr.
\ - escape character: printf fonksiyonu iin zel ilemler
belirler.
\n is the newline character: Alt satra ge.
; ;
Komutlarn sonuna ; konur.
C++ ve NESNEYE DAYALI PROGRAMLAMA 30
Deikenler bilgisayar belleindeki gzlere kar derler.
Her deikenin bir ad, boyu, bellek adresi, tipi ve deeri vardr.
Deikene yeni bir deer atandnda bellekteki eski deer
kaybolur.
Deikenlerin okunmas bellekteki deeri deitirmez.
45
sayi2
Bellek Gzleri Adres
3500
12
57
3501
3502
sayi1
Deiken ad
toplam
Bilgisayarlarn bellekleri saysal adreslere sahip gzlereden oluur.
Yksek dzeyli diller ile program yazan programclarn gerek bellek
adreslerini bilmelerine gerek yoktur. Bu nedenle deikenler
tanmlanr. Derleyici bu deikenler iin bellekte yer ayrr.
Bellek Kavram
Bellek Kavram Bellek Kavram
16
C++ ve NESNEYE DAYALI PROGRAMLAMA 31
Bir C programnda kullanlacak olan deikenlerin programn banda,
yrtlen deyimlerden nce tanmlanmalar gerekir.
Deiken tanmlanmas,
a) bilgisayar belleinde o deikenler iin yer ayrlmasn salar,
b) ilgili bellek gzlerinde sembolik isimler verilmesini salar.
Deiken simleri:
Harf, rakkam ve alt izigi '_' ierirler.
Harf veya '_' ile balamak zorundadr. '_' ile balamas nerilmez.
Byk/kk harf ayrm vardr.
C dilinin anahtar szckleri deiken ismi olarak kullanlamaz.
zel karakterler ve Trke'ye zg harfler (,,,,) kullanlamaz.
Geerli isimler:
a1, sayi, sayi_3, IlkDeger, SonSayi, a1c32, deneme_degeri
Geersiz isimler:
1a1, deer, int
Deiken Tanmlamalar
Deiken Tanmlamalar Deiken Tanmlamalar
C++ ve NESNEYE DAYALI PROGRAMLAMA 32
Programn anlalrlln salamak iin deikenlere, ilevleriyle ilikili
anlaml isimler verilmeli.
Birden fazla szckten oluan deikenlerde ikinci szck byk harf
ile balatlmal ya da araya '_' konulmal
Deiken Tipleri:
Deikenlerin kapladklar alanlar baz sistemlerde farkl olabilir.
Deiken tipi Anahtar szck Byte alma Aral
Karakter char 1 -128 ; 127
Tamsay int 2 -32768 ; 32767
Ksa tamsay short 2 -32768 ; 32767
Uzun tamsay long 4 -2,147,483,648 ; 2,147,483,647
aretsiz karakter unsigned char 1 0 ; 255
aretsiz tamsay unsigned int 2 0 ; 65535
aretsiz uzun ts. unsigned long 4 0 ; 4,294,967,295
Reel say float 4 1.2E-38 ; 3.4E38
ift hassas. r.s. double 8 2.2E-308 ; 1.8E308
Deiken Tanmlamalar
Deiken Tanmlamalar Deiken Tanmlamalar
17
C++ ve NESNEYE DAYALI PROGRAMLAMA 33
C/C++ tip denetimli bir dildir. Bu nedenle program
iinde her bir deiken mutlaka bir tip ile
ilikilendirilmelidir:
initial_value variable_name
Bellek Grnts
sizeof(type)
type variable_name = initial_value ;
Deiken Tanmlamalar
Deiken Tanmlamalar Deiken Tanmlamalar
C++ ve NESNEYE DAYALI PROGRAMLAMA 34
{ {
int x x = 12;
/* only x available */
{ {
int q q = 96;
/* both x & q available */
} }
/* only x available */
/* q is out of scope */
} }
Erim (= Scope) Kavram
Erim (= Scope) Kavram Erim (= Scope) Kavram
18
C++ ve NESNEYE DAYALI PROGRAMLAMA 35
Operatrleri aldklar operand saysna gre snfta
toplayabiliriz:
Tekli Operatrler Tekli Operatrler
++, --, !, +, -
kili Operatrler kili Operatrler
=, +=, == , <, +, -, *, /
l Operatr l Operatr ?:
Operatrler
Operatrler Operatrler
()
++ -- + - !
* / %
+ -
< <= > >=
== !=
&&
||
?:
= += -= *= /= %=
,
operatrler
aras ncelik
C++ ve NESNEYE DAYALI PROGRAMLAMA 36
a=1, b=1
a=1, b=0
a=2, b=2
a=2, b=3
nceden/Sonradan Arttrma/Azaltma ++/--
Operatrleri
nceden/Sonradan Arttrma/Azaltma ++/ nceden/Sonradan Arttrma/Azaltma ++/-- --
Operatrleri Operatrleri
int int a=0, a=0,b b=2; =2;
a = a = b b++ ++; ;
b b = = -- --a ; a ;
a = a = b b-- -- ; ;
b b = = ++ ++a ; a ;
19
C++ ve NESNEYE DAYALI PROGRAMLAMA 37
Atama Operatrleri
Atama Operatrleri Atama Operatrleri
a = a / b; a = a / b;
a a /= /= b ; b ;
int int a,b; a,b;
a = a + b; a = a + b;
a a += += b ; b ;
a = a a = a - - b; b;
a a - -= = b ; b ;
a = a * b; a = a * b;
a a *= *= b ; b ;
a = a % b; a = a % b;
a a %= %= b ; b ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 38
Karlatrma Operatrleri
Karlatrma Operatrleri Karlatrma Operatrleri
a == b a == b Eitlik Eitlik
a != b a != b Eitsizlik Eitsizlik
a > b a > b Byklk Byklk
a >= b Byk Eitlik a >= b Byk Eitlik
a < b a < b Kklk Kklk
a <= b Kk Eitlik a <= b Kk Eitlik
20
C++ ve NESNEYE DAYALI PROGRAMLAMA 39
Bit Dzeyinde lem Yapan Operatrler
Bit Dzeyinde lem Yapan Operatrler Bit Dzeyinde lem Yapan Operatrler
~ ~ DEL DEL
& & VE VE
| | VEYA VEYA
^ ^ Dar VEYA Dar VEYA
~ ~= = , , & &= = , , | |= = , ,^ ^= =
C++ ve NESNEYE DAYALI PROGRAMLAMA 40
true
Lojik Operatrler
Lojik Operatrler Lojik Operatrler
! ! Deil Deil
&& && VE VE
|| || VEYA VEYA
^^ ^^ Dar VEYA Dar VEYA
F T T
T F T
T T F
F F F
y y x x
int a = 0, b = 5, c= int a = 0, b = 5, c=- -2 ; 2 ;
( ( a || b) && c ) ( ( a || b) && c )
if(a == 5) if(a == 5)
if(a = 5) if(a = 5)
21
C++ ve NESNEYE DAYALI PROGRAMLAMA 41
-64
2147483616
-64
-32
Kaydrma Operatrleri
Kaydrma Operatrleri Kaydrma Operatrleri
<< << Sola Kaydrma Sola Kaydrma
>> >> Saa Kaydrma Saa Kaydrma
int a = -16 ;
a = a<<2 ;
printf(%d,a) ;
a = a>>1 ;
printf(%d,a) ;
unsigned int a = -16 ;
a = a<<2 ;
printf(%d,a) ;
a = a>>1 ;
printf(%d,a) ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 42
DZLER
DZLER DZLER
int c[12] ;
dizinin boyu
dizinin ad
dizinin tipi
indis deeri
22
C++ ve NESNEYE DAYALI PROGRAMLAMA 43
OK BOYUTLU DZLER
OK BOYUTLU DZLER OK BOYUTLU DZLER
int b[2][2] = {{1,2},
{3,4}} ;
ikinci boyut
birinci boyut
Balang deerleri satr
dzeninde verilmelidir.
indis deerleri
C++ ve NESNEYE DAYALI PROGRAMLAMA 44
Kontrol ve evrim Yaplar
Kontrol ve evrim Yaplar Kontrol ve evrim Yaplar
Dallanma Komutlar
if, if-else, switch
evrim Oluturma Komutlar
for( ; ; )
while()
do{...}while() ;
23
C++ ve NESNEYE DAYALI PROGRAMLAMA 45
if, if-else
if, if if, if- -else else
int sicaklik ;
...
if ( sicaklik <=18 )
printf(isit);
else
if ( sicaklik >= 26 )
printf(sogut);
printf( sicaklik <= 18 ? ? isit : : sogut );
lojik ifade lojik ifade true true false false
C++ ve NESNEYE DAYALI PROGRAMLAMA 46
if ( x > 5 ) if ( x > 5 )
if if ( y > 5 ) ( y > 5 )
printf printf( "x and y are > 5" ); ( "x and y are > 5" );
else else
printf printf( "x is <= 5" ); ( "x is <= 5" );
if ( x > 5 ) if ( x > 5 ){ {
if ( y > 5 ) if ( y > 5 )
printf printf( "x and y are > 5" ); ( "x and y are > 5" );
} }
else else
printf printf( "x is <= 5" ); ( "x is <= 5" );
24
C++ ve NESNEYE DAYALI PROGRAMLAMA 47
int int faktoriyel = 1, i=1 faktoriyel = 1, i=1; ;
while ( while ( i i <= <= 9 9 ) ){ {
faktoriyel faktoriyel *= *= i i; ;
i++; i++;
} }
print printf f(9!= (9!=%d %d , ,faktoriyel); faktoriyel);
i <= 9
faktoriyel *= i ;
true
false
while, do-while dngs
while, do while, do- -while dngs while dngs
C++ ve NESNEYE DAYALI PROGRAMLAMA 48
int int faktoriyel = 1, i=1 faktoriyel = 1, i=1; ;
do{ do{
faktoriyel faktoriyel *= *= i i; ;
i++ ; i++ ;
} }while ( while ( i i <= <= 9 9 ) ); ;
printf printf(9!= (9!=%d %d , ,faktoriyel) faktoriyel)
do{}while() do{}while()
25
C++ ve NESNEYE DAYALI PROGRAMLAMA 49
for dngs
for dngs for dngs
int int faktoriyel,sum,i faktoriyel,sum,i; ;
for for( (i=1,faktoriyel,sum=0 i=1,faktoriyel,sum=0; ;i<=9 i<=9; ;sum+=i,i++ sum+=i,i++) )
faktoriyel faktoriyel *= *= i i; ;
print printf f(9!= (9!=%d %d , ,faktoriyel) faktoriyel)
C++ ve NESNEYE DAYALI PROGRAMLAMA 50
void main main() {
for for(int i = 0; i < 100; i++) {
if(i == 74) break break; // Out of for loop
if(i % 9 != 0) continue continue; // Next iteration
printf(%d,i);
}
int i = 0;
while(true) {
i++;
int j = i * 27;
if(j == 1269) break break; // Out of loop
if(i % 10 != 0) continue continue; // Top of loop
printf(%d,i);
} }}
26
C++ ve NESNEYE DAYALI PROGRAMLAMA 51
Kendi iinde bamsz olarak alabilen ve belli bir ilevi yerine getiren
program modlleridir.
C programlar bu modllerden (fonksiyonlar) oluurlar.
Fonksiyonlarn yazlmasndaki temel ama; byk boyutlardaki
programlarn daha kolay yazlabilen ve test edilebilen kk paralar halinde
oluturulabilmesidir (Bl ve ynet).
Fonksiyonlar zellikleri:
Her fonksiyonun bir ad vardr. Fonksiyon isimlerinin verilmesinde deiken
isimlerinde uygulanan kurallar geerlidir.
Fonksiyonlar programn dier paralarndan etkilenmeden bamsz bir
ilem yapabilirler.
Belli bir ilevi yerine getirirler. rnein, ortalama hesaplamak, ekrana bir
veri yazmak, bir dizideki en byk eleman bulmak gibi.
Kendilerini aran programdan parametre olarak veri alabilirler.
Gerektii durumlarda rettikleri sonular kendilerini aran programa
parametre olarak geri gnderirler.
Fonksiyonlar
Fonksiyonlar Fonksiyonlar
C++ ve NESNEYE DAYALI PROGRAMLAMA 52
/* Fonksiyon rnei. Kp hesaplayan fonksiyon*/
#include <stdio.h>
/* Fonksiyon: kup Bir tamsaynn kpn hesaplar */
long int kup(int x)
{
long yardimci; // Yerel deiken
yardimci = x * x * x;
return yardimci;
}
/* Ana program */
void main()
{
int giris;
long int sonuc;
printf("Bir say giriniz: ");
scanf("%d", &giris);
sonuc = kup(giris); // Fonksiyon arlyor
printf("\n%d ss 3= %ld\n", giris, sonuc);
}
Geri Dn deerinin tipi
Fonksiyon ad
Giri parametresi
Yerel deiken.
Sadece fonksiyonun iinde geerli
Sonu, aran programa
gnderiliyor
Fonksiyon arlyor
Fonksiyona giden deer
Fonksiyondan gelen deerin
yazlaca bellek gz
rnek
rnek rnek
27
C++ ve NESNEYE DAYALI PROGRAMLAMA 53
Karmak problemler daha kk paralara blnebilir. Her
para ayr ayr fonksiyonlar eklinde zlerek sonradan ana
programda birletirilebilir.
Grup almalar iin uygun bir ortam hazrlar. Grup elemanlar
bamsz fonksiyonlar ayr ayr tasarlarlar. Son aamada bu
fonksiyonlar ana programda birletirilir.
Daha nceden yazlm fonksiyonlar arivlerden alnarak
kullanlabilir. Ayn program parasnn tekrar yazlmasna gerek
kalmaz.
Programn iinde sk sk tekrar edilen blmler fonksiyon
olarak yazlabilir. Bylece ayn program parasnn defalarca
tekrar edilmesine gerek kalmaz.
Fonksiyonlarn Salad Yararlar
Fonksiyonlarn Salad Yararlar Fonksiyonlarn Salad Yararlar
C++ ve NESNEYE DAYALI PROGRAMLAMA 54
Main (aran)
--- ---
--- ---
--- ---
--- ---
--- ---
y= y=kup(b kup(b); );
---
---
---
Fonksiyon
---
---
---
---
---
---
return
x= x=kup(a kup(a); );
---
---
Sonraki deyim
Sonraki deyim
Fonksiyonlarn Tanmlanmas:
geri_dn_deeri_tipi fonksiyon_ad ( parametre listesi )
{
deyimler
return <deiken/sabit/ifade>;
}
Fonksiyonlarn leyii
Fonksiyonlarn leyii Fonksiyonlarn leyii
28
C++ ve NESNEYE DAYALI PROGRAMLAMA 55
Eer fonksiyon geriye deer dndrmeyecekse geri dn deerinin
tipi void olarak tanmlanr. Bu durumda fonksiyondan k
salayan return szcnn yanna bir deer yazlmaz. Bu tr
fonksiyonlarda istenirse return szc yazlmayabilir.
rnein: ki tamsayy ekrana yazan fonksiyon
void yaz(int a, int b)
{
printf("\nsay1=%d say2=%d", a, b);
return; // Bu satr yazlmayabilir.
}
/** Ana Program (Ana fonksiyon) **/
void main()
{
int i1=450, i2=-90;
yaz(i,23);
yaz(18,i2);
yaz(i1, i2);
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 56
Bir fonksiyonda birden fazla return szc (k noktas) olabilir.
rnein: ki tamsaynn byk olann bulan ve aran programa
gnderen fonksiyon.
#include <stdio.h>
int buyuk( int a, int b){
if (a > b) return a;
else return b;
}
void main()
{
int x, y, z;
printf("\nki say giriniz: ");
scanf("%d%d", &x, &y);
z = buyuk(x,y);
printf("\nDaha byk olan: %d.", z);
}
29
C++ ve NESNEYE DAYALI PROGRAMLAMA 57
Fonksiyonlar isimleri yazlarak ve parantez iinde gerekli sayda
argman gnderilerek arlr.
Eer fonksiyon geriye bir deer dndryorsa, bu deer bir deikene
atanabilir, baka bir fonksiyona argman olarak verilebilir, bir ifadenin
iinde kullanlabilir.
rnein: Bir tamsaynn yarsn hesaplayan ve aran programa
gnderen fonksiyon.
float yarisi( int a)
{
return (a/2.0);
}
Bu fonksiyon aadaki satrlarda gsterildii gibi arlabilir.
x=yarisi(5);
z=yarisi(i) + 3*yarisi(k);
printf("\n Saynn yars= %f", yarisi(sayi));
f=yarisi((int)yarisi(x));
Fonksiyonlarn arlmas
Fonksiyonlarn arlmas Fonksiyonlarn arlmas
C++ ve NESNEYE DAYALI PROGRAMLAMA 58
Yerel Deiken / Global Deiken:
Fonksiyonlarn gvdelerinin iinde ({ } arasnda) tanmlanan deikenler
sadece o fonksiyonda (main veya dier) kullanlabilen yerel
deikenlerdir. O fonksiyon sona erdikten sonra yerel deikenler
bellekten kaldrlrlar. Fonksiyon gvdelerinin dnda tanmlanan
(rnein main'in stnde) deikenler ise global deikenlerdir. Bu
deikenler btn fonksiyonlar tarafndan yazlp okunabilirler ve
programn almas sresince geerlidirler.
#include <stdio.h>
float f; // Global deiken
int long kup(int x)
{
long yardimci; // kup'e ait yerel deiken
yardimci = x * x * x;
return yardimci;
}
/* Ana program */
void main()
{
int giris; // main'e ait yerel deiken
rnein; yandaki program
parasnda f global
deikendir ve tm
fonksiyonlar tarafndan
kullanlabilir.
yardimici adl deiken
sadece kup adl fonksiyonda
kullanlabilir.
giris adl deiken ise sadece
main iinde kullanlabilir.
30
C++ ve NESNEYE DAYALI PROGRAMLAMA 59
int x = 1, y = 2; // Global Deikenler
void demo() { // Parametre almyor, deer dndrmyor
int x = 88, y = 99; // yerel deikenler
printf("\nFonkisyonun iinde, x = %d y = %d.", x, y);
}
void main() { /*** Ana program ***/
printf("\nFonksiyonu armadan nce, x = %d y = %d.", x, y);
demo();
printf("\nFonksiyonu ardktan sonra, x = %d y = %d", x, y);
}
rnek: rnek: Aadaki rnekte ayn global ve yerel deikenler ayn isimde
tanmlanm (x ve y). Bu durumda fonksiyonun iinde x ve y isimleriyle sadece
yerel deikenlere eriilir.
Aadaki olumsuz ynlerinden dolay global deiken kullanmndan kanmak
gerekir:
Global deikenler btn fonksiyonlar tarafndan deitirilebildii iin
programdaki hatalarn ayklanmasn zorlatrrlar.
Grup elemanlar arasndaki bamllk artar. Hangi global deikenin ne ilevi
olacana, ismine ve kimin tarafndan ne ekilde deitirileceine nceden karar
vermek gerekir.
C++ ve NESNEYE DAYALI PROGRAMLAMA 60
C dilinde, alfabetik szckler (string) karakter dizisi eklinde tanmlanr :
char sozcuk[8]; // 7 char sozcuk[8]; // 7 harflik harflik bir bir szck szck tayabilir tayabilir. .
void main() void main()
{ {
sozcuk sozcuk=" ="merhaba merhaba"; ";
printf(" printf("\ \n n Mesaj Mesaj: % : %s",sozcuk s",sozcuk); );
} }
sozcuk[0]
sozcuk[1]
sozcuk[2]
sozcuk[3]
sozcuk[4]
sozcuk[5]
sozcuk[6]
sozcuk[7]
Karakter katarnn her eleman bir karakter
ierir.
Karakter katarlarna ilikin deerler iki adet
ift trnak (") iinde yazlr.
Bir karakterlik deerler tek trnak (') iaretleri
arasnda yazlr
'\0' Karakter katarnn sona erdiini belirten
zel bir karakterdir.
Karakter Katar (= String)
Karakter Katar (= String Karakter Katar (= String) )
m m
e e
r r
h h
a a
b b
a a
\ \0 0
31
C++ ve NESNEYE DAYALI PROGRAMLAMA 61
/* String: Karakter Dizisi */
#include <stdio.h>
void main()
{
char isim[20];
char mesaj[ ] = "Merhaba";
int i;
printf(" Adnz giriniz: ");
scanf( "%s", isim );
printf( "\n%s %s\n Naslsn?\n",mesaj, isim );
printf("\Harflerin arasnda birer boluk brakarak adnz:\n");
for ( i = 0; isim[ i ] != '\0'; i++ )
printf( "%c ", isim[ i ] );
printf( "\n" );
}
Bkz. string.c
20 harflik yer ayrlyor
8 harflik yer ayrlyor.
Balang deeri "merhaba"
scanf ile string okunurken
bana & yazlmaz
karakter katarlar
ekrana yazlrken %s kullanlr
isim katarnn i. harfi
katarnn son harfi: \0
rnek
rnek rnek
C++ ve NESNEYE DAYALI PROGRAMLAMA 62
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
C++, Cnin bir st kmesidir,
Cde yazdnz kodlar bir C++ derleyicisi ile derleyebilirsiniz,
C++n nesneye dayal olmayan zelliklerini C program
yazarken kullanabilirisiniz.
Aklama satrlar
/* This is a comment */
// This is a comment
C++da tanmlamay programn istediiniz yerinde
yapabilirsiniz. Bu programn okunabilirliini arttracaktr.
32
C++ ve NESNEYE DAYALI PROGRAMLAMA 63
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
int a=0;
for (int i=0; i < 100; i++){ { // i is declared in for loop
a++;
int p=12; // Declaration of p
... // Scope of p
} } // End of scope for i and p
devam
C++ ve NESNEYE DAYALI PROGRAMLAMA 64
Erim (=scope) Operatr :: ::
Kural olarak Cde her deiken tanml olduu blok
ierisinde erime sahiptir.
int x=1;
void f(){
int x=2; // Local x
x++; // Local x is 3
}
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
devam
33
C++ ve NESNEYE DAYALI PROGRAMLAMA 65
int x x=1;
void f(){
int x=2; // Local x
::x ::x++; // Global x is 2
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 66
int i=1;
main(){
int i=2;
{
int n=i ;
int i = 3 ;
cout << i << " " << ::i << endl ;
cout << n << "\n" ;
}
cout << i << " " << ::i << endl;
return 0 ;
}
3 1 3 1
2 2
2 1 2 1
34
C++ ve NESNEYE DAYALI PROGRAMLAMA 67
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
inline fonksiyonlar
Cdeki makrolara gre aadaki avantajlara sahiptir
Hata ayklama
Tip denetimi
Kolay izlenebilir
inline inline int int SQ(int SQ(int x){return (x*x); } x){return (x*x); }
#define #define sq( sq(x) (x*x) x) (x*x)
devam
C++ ve NESNEYE DAYALI PROGRAMLAMA 68
Tip belirtilmemi ise
derleyici tipi int kabul
eder.
inline inline int int max max( (int int x x,int y ,int y){return ( ){return (y<x ? x : y) y<x ? x : y); } ; }
#define #define max( max(x x,y ,y) ( ) (y<x ? x : y y<x ? x : y) )
#define #define false 0 false 0
#define #define pi 3.14159 pi 3.14159
const false = 0 ; const false = 0 ;
const const double pi = 3.14159 ; double pi = 3.14159 ;
const const double e = 2.71828; double e = 2.71828;
const M_Size = 100 ; const M_Size = 100 ;
const *p=&M_Size ; const *p=&M_Size ;
char * const s= char * const s= "abcde abcde" ; ;
35
C++ ve NESNEYE DAYALI PROGRAMLAMA 69
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
Fonksiyon Parametrelerine Balang Deeri atayabilme
int e(int n,int k=2 k=2){
if(k == 2)
return (n*n) ;
else
return ( mult(n,k-1)*n ) ;
}
e(i+5)
// (i+5)* (i+5)
e(i+5,3)
// (i+5)in kubu
devam
C++ ve NESNEYE DAYALI PROGRAMLAMA 70
void f(int i, int j=7) ; // dogru
void g(int i=3, int j) ; // yanlis
void h(int i, int j=3,int k=7) ; // dogru
void m(int i=1, int j=2,int k=3) ; // dogru
void n(int i=2, int j,int k=3) ; // dogru ? ? yanlis
36
C++ ve NESNEYE DAYALI PROGRAMLAMA 71
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
Referans Operatr & &
Bir deikenin adres bilgisine erimek iin kullanlr.
ki farkl kullanm biimi vardr:
int n ;
int& nn = n ;
double a[10] ;
double& last = a[9] ;
const char& new_line = '\n' ;
devam
C++ ve NESNEYE DAYALI PROGRAMLAMA 72
void swap(int a, int b){
int temp = a ;
a = b ;
b = temp ; }
ki deikenin ieriini takas eden fonksiyon :
swap()
main(){
int i=3,j=5 ;
swap(i,j) ;
cout << i << " " << j << endl ;
}
3 5 3 5
5
GDA
3
sistem yn
b=5
GDA
a=3
5
3
3
3 i
j
a
b
bellek
37
C++ ve NESNEYE DAYALI PROGRAMLAMA 73
void swap(int *a, int *b){
int temp = *a ;
*a = *b ;
*b = temp ; }
main(){
int i=3,j=5 ;
swap(&i,&j) ;
cout << i << " " << j << endl ;
}
5 3 5 3
adr_j
GDA
adr_i
*b=5
GDA
*a=3
5
adr
adr
3 i
j
a
b
bellek
C++ ve NESNEYE DAYALI PROGRAMLAMA 74
void swap(int& a,int& b){
int temp = a ;
a = b ;
b = temp ; }
main(){
int i=3,j=5 ;
swap(i,j) ;
cout << i << " " << j << endl ;
}
3 5 3 5
38
C++ ve NESNEYE DAYALI PROGRAMLAMA 75
void shift(int& a1,int& a2,int& a3,int& a4){
int tmp = a1 ;
a1 = a2 ;
a2 = a3 ;
a3 = a4 ;
a4 = tmp ;
}
main(){
int x=1,y=2,z=3,w=4;
cout << x << y << z << w << endl;
shift(x,y,z,w) ;
cout << x << y << z << w << endl;
return 0 ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 76
main(){
int x=2,y=3,z=4 ;
squareByPointer(&x) ;
cout << x << endl ;
squareByReference(y) ;
cout << y << endl ;
z = squareByValue(z) ;
cout << z << endl ;
}
int squareByValue(int a){
return (a*a) ;
}
void squareByPointer(int *aPtr){
*aPtr *= *aPtr ;
}
void squareByReference(int& a){
a *= a ;
}
4 4
9 9
16 16
39
C++ ve NESNEYE DAYALI PROGRAMLAMA 77
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
Dinamik Bellek Kullanm
Cde dinamik bellek kullanm standart ktphaneler
kullanlarak gerekletirilmektedir:
int *p ; p = (int *) malloc(N*sizeof(int)) ; free(p) ;
C++da iki yeni operatr : new new ve delete delete
int *p ;
p = new new int[N] ;
delete delete []p ;
int *p,*q ; int *p,*q ;
p = new int[9] ; p = new int[9] ;
q = new int(9) ; q = new int(9) ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 78
ki boyutlu matris
double ** q ;
q = new double*[row] ; // rowxcolumnlik bir matris
for(int i=0;i<row;i++)
q[i] = new double[column] ;
..
for(int i=0;i<row;i++)
delete q[i] ;
delete []q ;
i. satr j. stun elemanna eriim : q[i][j]
40
C++ ve NESNEYE DAYALI PROGRAMLAMA 79
ki boyutlu matris
double ** q,*t ;
p = new double*[row] ; // rowxcolumnlik bir matris
t = new double[row*column] ;
for(int i=0,col=0;i<row;i++,col+=column)
q[i] = t + col ;
..
delete q[0] ;
delete q ;
i. satr j. stun elemanna eriim : q[i][j]
C++ ve NESNEYE DAYALI PROGRAMLAMA 80
double ** q,*t ;
memoryAlign = column % 4 ;
memoryWidth = ( memoryAlign == 0 ) ?
column : (column+4 -memoryAlign) ;
p = new double*[row] ; // rowxmemoryWidthlik bir matris
t = new double[row*memoryWidth] ;
for(int i=0,col=0;i<row;i++,col+=memoryWidth)
q[i] = t + col ;
..
delete q[0] ;
delete q ;
41
C++ ve NESNEYE DAYALI PROGRAMLAMA 81
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
Fonksiyon Ykleme (=Function Overloading)
double average average(const double a[],int size) ;
double average average(const int a[],int size) ;
double average average(const int a[], const double b[],int size) ;
double average(const int a[],int size) {
double sum = 0.0 ;
for(int i=0;i<size;i++) sum += a[i] ;
return ((double)sum/size) ;
}
devam
C++ ve NESNEYE DAYALI PROGRAMLAMA 82
double average(const double a[],int size) {
double sum = 0.0 ;
for(int i=0;i<size;i++) sum += a[i] ;
return (sum/size) ;
}
double average(const int a[],const double b[],int size) {
double sum = 0.0 ;
for(int i=0;i<size;i++) sum += a[i] + b[i] ;
return (sum/size) ;
}
42
C++ ve NESNEYE DAYALI PROGRAMLAMA 83
main() {
int w[5]={1,2,3,4,5} ;
double x[5]={1.1,2.2,3.3,4.4,5.5} ;
cout << average(w,5) ;
cout << average(x,5) ;
cout << average(w,x,5) ;
return 0 ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 84
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
Function Templates
template <class T>
void printArray(T *array,cont int size){
for(int i=0;i < size;i++)
cout << array[i] << " " ;
cout << endl ;
}
devam
43
C++ ve NESNEYE DAYALI PROGRAMLAMA 85
main() {
int a[3]={1,2,3} ;
double b[5]={1.1,2.2,3.3,4.4,5.5} ;
char c[7]={a, b, c, d, e , f, g} ;
printArray(a,3) ;
printArray(b,5) ;
printArray(c,7) ;
return 0 ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 86
void printArray(int *array,cont int size){
for(int i=0;i < size;i++)
cout << array[i] << ," ;
cout << endl ;
}
void printArray(char *array,cont int size){
for(int i=0;i < size;i++)
cout << array[i] ;
cout << endl ;
}
44
C++ ve NESNEYE DAYALI PROGRAMLAMA 87
lev Ykleme
lev Ykleme
C++da yerleik operatrlere (+, -, = ve ++ gibi) aldklar
operandlarn tipine gre yeni ilevler yklenebilir. Aada rnek
olarak ki karmak sayy toplamak iin + operatrne yeni ilev
yklenmitir:
struct ComplexT{
float real,img;
};
ComplexT operator+(ComplexT v1, ComplexT v2){
ComplexT result;
[Link]=[Link]+[Link];
[Link]=[Link]+[Link];
return result;
}
void main(){
ComplexT c1,c2,c3;
c3=c1+c2; // c1+(c2)
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 88
C++n Cye Getirdii Gelimi zellikler
C++n Cye Getirdii Gelimi zellikler C++n Cye Getirdii Gelimi zellikler
#include <string>
#include <iostream>
using namespace std;
int main() {
string test;
while([Link]() || [Link]() <= 5)
{
cout << "Type a string longer string. " << endl;
cin >> test;
}
printf(%s,s.c_str()) printf(%s,s.c_str())
45
C++ ve NESNEYE DAYALI PROGRAMLAMA 89
#include <iostream>
namespace F {
float x = 9;
}
namespace G {
using namespace F;
float y = 2.0;
namespace INNER_G {
float z = 10.01;
}
}
int main(void) {
float x = 19.1;
using namespace G;
using namespace G::INNER_G;
std::cout << "x = " << x << std::endl;
std::cout << "y = " << y << std::endl;
std::cout << "z = " << z << std::endl;
return 0;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 90
Nesneye Dayal Programlama Kavramlar
Nesneye Dayal Programlama Kavramlar Nesneye Dayal Programlama Kavramlar
Fonksiyonel programlamada probleme
Verilen problemin zm iin algoritma algoritmay hangi
fonksiyon fonksiyonlara paralamalym ?
sorusu ile yaklalr.
Nesneye dayal programlamada ise
Verilen problemin zm iin veri veriyi hangi nesne nesnelere
paralamalym ?
sorusu ile yaklalr. Nesneye dayal programlamada temel
tasarm eleman nesnelerdir.
46
C++ ve NESNEYE DAYALI PROGRAMLAMA 91
Nesneye Dayal Programlama Kavramlar
Nesneye Dayal Programlama Kavramlar Nesneye Dayal Programlama Kavramlar
Nesneye dayal bir dil kullanlarak problem zlrken,
programc, problemin zm iin programn hangi
fonksiyonlara blnmesi gerektiini dnmek yerine, hangi
nesnelere blnmesi gerektiini dnecektir.
Nesneye dayal dnmek, sadece programn daha kolay
oluturulmasn salamayacak, ayn zamanda daha kolay
modellenebilmesini salayacaktr. Bu programlama
anlamndaki nesne ile gerek dnyadaki nesne arasndaki yakn
ilikiden kaynaklanmaktadr.
nsanlar olaylar zihinlerinde nesneler biiminde canlandrr.
C++ ve NESNEYE DAYALI PROGRAMLAMA 92
rnek : Bir binann asansr sistemi
rnek : Bir binann asansr sistemi rnek : Bir binann asansr sistemi
c current urrentF Floor loorN Number umber
n number umberOfP OfPassengers assengersA Aboard board
l list istOfB OfButtons uttonsP Pushed ushed
g getInfo etInfo() ()
c calculateWhereToGo alculateWhereToGo() ()
g goDown oDown() ()
g goUp oUp() ()
CloseDoors CloseDoors() ()
o openDoors penDoors() ()
durum
davran
47
C++ ve NESNEYE DAYALI PROGRAMLAMA 93
class class Time{
public:
Time();
void SetTime(int,int,int) ;
void PrintTime() ;
private:
int hour ; // 0-23
int minute; // 0-59
int second; // 0-59
}
C++da Snf (=Class) Yaps
C++da Snf (= C++da Snf (=Class Class) Yaps ) Yaps
struct Time{
int hour ; // 0-23
int minute; // 0-59
int second; // 0-59
}
veri
fonksiyonlar fonksiyonlar ? ?
class class Time{
public:
Time();
void SetTime(int,int,int) ;
void PrintTime() ;
private:
int hour ; // 0-23
int minute; // 0-59
int second; // 0-59
}
davran
durum
C++ ve NESNEYE DAYALI PROGRAMLAMA 94
void Time::Time(){ hour=minute=second=0;}
void Time::SetTime(int h,int m,int s){
hour = (h>=0 && h<24) ? h : 0 ;
minute = (m>=0 && m<60) ? m : 0 ;
second = (s>=0 && s<60) ? s : 0 ;
}
void Time::PrintTime(){
cout << ((hour == 0) || (hour == 12) ? 12 : hour%12)
<< ":" << (minute < 10) ? "0" : "") << minute
<< ":" << (second < 10) ? "0" : "") << second
<< (hour < 12 ? " AM" : " PM") ;
}
48
C++ ve NESNEYE DAYALI PROGRAMLAMA 95
void main(){
Time t ;
[Link]();
[Link](13,27,16) ;
[Link]();
[Link](99,99,99) ;
[Link]();
cout << endl ;
return 0 ;
}
12:00:00 AM 12:00:00 AM
1:27:16 PM 1:27:16 PM
12:00:00 AM 12:00:00 AM
VER
hour,
minute, second
NESNE : Time
FONKSYONLAR
Time
SetTime
PrintTime
[Link](13,27,16);
[Link]();
C++ ve NESNEYE DAYALI PROGRAMLAMA 96
Nesne aretileri
Nesne aretileri Nesne aretileri
void main(){
Time * *t ;
t = new newTime ;
t- -> >PrintTime();
t- -> >SetTime(13,27,16) ;
t- -> >PrintTime();
t- -> >SetTime(99,99,99) ;
t- -> >PrintTime();
cout << endl ;
return 0 ;
}
12:00:00 AM 12:00:00 AM
1:27:16 PM 1:27:16 PM
12:00:00 AM 12:00:00 AM
49
C++ ve NESNEYE DAYALI PROGRAMLAMA 97
C++ Terminolojisi
C++ Terminolojisi C++ Terminolojisi
Snf : veriler ve o veriler zerinde ilem yapan fonksiyonlar
grubudur. Cdeki struct yapsna olduka benzer. Program iinde
bir deiken iin kullanlabilecek yeni bir tip oluturmaktadr.
Nesne : Belirli bir tipten yaratlan deiken gibi belirli bir
snftan yaratlan bir kopyadr. Program dorudan nesneler
zerinde ilem yapar.
Metod : Nesneye dayal programlamada, bir snf iinde
tanmlanan ye fonksiyonlara metod ad verilmektedir.
Mesaj : Nesneye dayal programlamada bir snfa ait bir ye
fonksiyonunun arlmasna nesneye dayal programlamada
mesaj denir.
C++ ve NESNEYE DAYALI PROGRAMLAMA 98
class Time { Snf Tanm
int hour; Nitelikler
int minute;
int second ;
public:
void SetTime(int h,int m,int s){hour=h;minute=m;second=s} 1. 1. metod metod
void PrintTime(); 2. metod
};
void Time::PrintTime() 2. 2. Metod Metodun gvdesi un gvdesi
{
cout << ((hour == 0) || (hour == 12) ? 12 : hour%12)
<< ":" << (minute < 10) ? "0" : "") << minute
<< ":" << (second < 10) ? "0" : "") << second
<< (hour < 12 ? " AM" : " PM") ;
}
void main()
{
Time t; t nesnesi yaratld
[Link](13,26,6); nesneye bir mesaj gnderiliyor
[Link](); nesneye bir baka mesaj
gnderiliyor
}
[Link]
p
50
C++ ve NESNEYE DAYALI PROGRAMLAMA 99
void main()
{
Time t;
[Link] = 13 ;
[Link] = 26 ;
[Link] = 6 ;
[Link]();
}
class Time { Snf tanm
int hour; Nitelikler
int minute;
int second ;
public:
void SetTime(int h,int m,int s){hour=h;minute=m;second=s;} ; 1. 1. metod metod
void PrintTime(); 2. metod
};
Error:
Time::hour is not accessable
Time::minute is not accessable
Time::second is not accessable
C++ ve NESNEYE DAYALI PROGRAMLAMA 100
Public
Public yelere programdaki herhangi bir fonksiyon tarafndan
eriilebilir.
Private
Herhangi bir tanmlama yok ise varsaylan tanmlama privatedir.
Private yeler sadece o snfa ait yeler veya o snfn friend yeleri
tarafndan eriilebilir.
Protected (Public ile Private arasnda)
Private yeler sadece o snfa ait yeler, o snftan tretilmi snflarn
yeleri veya o snfn friend yeleri tarafndan eriilebilir.
Nesne yelerine Eriimin Denetlenmesi
Nesne yelerine Eriimin Denetlenmesi Nesne yelerine Eriimin Denetlenmesi
? ?
51
C++ ve NESNEYE DAYALI PROGRAMLAMA 101
class Point {
public:
void SetPoint(float, float); // set coordinates
float GetX() const { return x; }; // get x coordinate
float GetY() const { return y; }; // get y coordinate
private: // accessible by derived classes
float x, y; // x and y coordinates of the Point
};
void Point::SetPoint(float a,float b){ x=a; y=b; }
main(){
Point p;
p.x=1; //[Link](1,2);
p.y=2;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 102
class Time {
int hour;
int minute;
int second ;
public:
// Get Functions // Get Functions
void SetTime(int h,int m,int s){hour=h;minute=m;second=s;};
void SetHour(int h){hour= (h>=0 && h<24) ? h : 0;} ; void SetHour(int h){hour= (h>=0 && h<24) ? h : 0;} ;
void SetMinute(int m){minute= (m>=0 && m<60) ? m : 0;} ; void SetMinute(int m){minute= (m>=0 && m<60) ? m : 0;} ;
void SetSecond(int s){second= (s>=0 && s<60) ? s : 0;} ; void SetSecond(int s){second= (s>=0 && s<60) ? s : 0;} ;
// Get Functions // Get Functions
int GetHour(){return hour;} ; int GetHour(){return hour;} ;
int GetMinute(){return minute;} ; int GetMinute(){return minute;} ;
int GetSecond (){return second;} ; int GetSecond (){return second;} ;
void PrintTime();
};
52
C++ ve NESNEYE DAYALI PROGRAMLAMA 103
Bir snfn friend fonksiyonlar ve snflar
Bir snfn Bir snfn friend friend fonksiyonlar ve snflar fonksiyonlar ve snflar
Bir fonksiyon yada bir snf bir baka snfn friend friendi olarak
tanmlanabilir. Bu durumda friend friend olarak tanmlanan fonksiyon yada
snfn yeleri o snfn tm yelerine eriebilir.
class A class A{
friend friend class B class B; // Class B is a friend of class A
private private: :
int int i i;
float f;
public:
void fonk1(char *c);
};
class B class B{
int j;
public:
void fonk2(A s A s){ cout << s. s.i i << endl ;} // B can access private members of A
};
C++ ve NESNEYE DAYALI PROGRAMLAMA 104
class ComplexT{
friend void print(ComplexT); // print function is a friend of ComplexT
float real,img; // private
:
};
void print(ComplexT z) // is not a member of ComplexT but a friend
{
cout << [Link] << " + i " << [Link]);
}
53
C++ ve NESNEYE DAYALI PROGRAMLAMA 105
zel bir iareti : this
zel bir iareti : zel bir iareti : this this
hour=7
minute=42
second=12
t1
t2
SetTime()
PrintTime()
hour=3
minute=12
second=53
Nesne = Veri + Fonksiyon
Her nesnenin veri alan bellekte farkl alana yerletirilmitir. Ancak
fonksiyonlar iin bir kez yer alnr ve o snftan tm nesneler ayn
fonksiyon alann kullanrlar.
Bu durumda fonksiyon hangi nesnenin verisini ileyeceini nereden biliyor ?
veri
veri
fonksiyonlar
C++ ve NESNEYE DAYALI PROGRAMLAMA 106
class dlink{
dlink *previous;
dlink *next;
public:
void insert(dlink *); // inserts a new node into the list
};
void dlink::insert(dlink * p)
{
p-> next = next;
p-> previous =this;
next -> previous =p;
next =p;
}
:
dlink dl1,dl2;
:
[Link](&dl2);
Bir ye fonksiyon arldnda, nesnenin adresini tayan this adl zel
bir iareti arlan fonksiyona parametre olarak aktarlr.
54
C++ ve NESNEYE DAYALI PROGRAMLAMA 107
C++ programnza #include <iostream.h> satr eklerseniz drt
tane nesne yaratlr:
cin
("see-in okunur) standart giri cihazndan (tu takm) deer okur.
cout
("see-out" okunur) standart k cihazna (ekran) deer yazar.
cerr ("see-err" okunur) standart hata cihazna (ekran)
tamponlanmam hatalar yazar.
clog ("see-log" okunur) standart hata cihazna (ekran)
tamponlanm hatalar yazar.
Giri/k : <iostream.h>
Giri/k : < Giri/k : <iostream.h> iostream.h>
C++ ve NESNEYE DAYALI PROGRAMLAMA 108
Ekrana bir deer yazmak iin, cou cout tu izleyen << << operatrn
kullanmanz gerekir:
#include<iostream.h>
void main() {
int i=5;
float f=4.6;
cout << "Integer Number = " << i << " Real Number=" << f;
}
Klavyeden bir deer okumak iin ise, cin cini izleyen >> >>
operatrn kullanmanz gerekir:
#include<iostream.h>
void main() {
int i,j;
cout << "Give to Numbers" << endl ;
cin >> i >> j;
cout << "Sum= " << i + j << "\n";
}
55
C++ ve NESNEYE DAYALI PROGRAMLAMA 109
Nesnelere Balang Deeri Verilmesi :
Kurucu Fonksiyonlar
Nesnelere Balang Deeri Verilmesi : Nesnelere Balang Deeri Verilmesi :
Kurucu Fonksiyonlar
Snflar, kurucu (= constructor) fonksiyon ad verilen zel bir ye
fonksiyona sahiptirler.
Kurucu fonksiyonun ad snf ad ile ayndr.
Kurucu fonksiyonlar parametre alabilirler, ancak bir deer
dndrmezler.
Kurucu fonksiyonlar, bir nesne yaratldnda dorudan derleyici
tarafndan arlr. Ama snf yelerine balang deerlerinin
verilmesidir.
C++ ve NESNEYE DAYALI PROGRAMLAMA 110
class ComplexT{
float real,img;
public:
ComplexT(){ // kurucu fonksiyon
real=0;
img=0;
}
};
void main()
{
ComplexT z1,z2; // kurucu iki defa cagrilir
ComplexT *zp = new ComplexT; // kurucu bir kez cagrilir
}
56
C++ ve NESNEYE DAYALI PROGRAMLAMA 111
class ComplexT{
float real,img;
public:
ComplexT(float r){real=r; img=0;} ;
ComplexT(float r,float i){real=r; img=i;};
: // diger uye fonksiyonlar
};
void main()
{
ComplexT z1(0.3);
ComplexT z2(0.5 , 1.2);
ComplexT *zp=new ComplexT(0.4);
ComplexT z3; // Hata!!!
//Could not find a match for ComplexT:: ComplexT()
}
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 112
Kopyalayc Kurucular
Kopyalayc Kurucular Kopyalayc Kurucular
Kopyalayc kurucu fonksiyonlar, o snftan bir nesnenin yelerini
yeni bir nesneye kopyalamakta kullanlr. Bu nedenle
parametrelerden biri ayn snftan bir nesnedir.
Eer programc tarafndan tanmlanmam ise derleyici bir tane
yaratr. Yaratlan kurucu fonksiyon nesnenin birebir kopyasn
oluturur.
class string{
int size;
char *contents;
public:
string(); // default constructor
string(string &); // copy constructor
void set (int, char *); // An ordinary member function
void print();
};
57
C++ ve NESNEYE DAYALI PROGRAMLAMA 113
string::string() // Kurucu fonksiyon
{
size = 0; contents = new char[1];
strcpy(contents, "");
}
string::string(string &in_object) // Kopyalayc kurucu fonksiyon
{
size = in_object.size;
contents = new char[strlen(in_object.contents)];
strcpy(contents, in_object.contents);
}
void string::set(int in_size, char *in_data)
{
size = in_size;
delete contents; contents = new char[strlen(in_data)];
strcpy(contents, in_data);
}
void string::print()
{
cout<< contents << " " << size << endl;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 114
void main()
{
string my_string;
my_string.set (8, "string 1");
my_string.print();
string other=my_string; // Copy constructor is invoked
string more(my_string); // Copy constructor is invoked
[Link]();
[Link]();
}
[Link]
[Link]
58
C++ ve NESNEYE DAYALI PROGRAMLAMA 115
Nesne Dizilerine Balang Deeri Verilmesi
Nesne Dizilerine Balang Deeri Verilmesi Nesne Dizilerine Balang Deeri Verilmesi
Nesne dizilerinde kurucu fonksiyon her dizi eleman iin teker
teker arlr:
class ComplexT{
float real, img;
public:
ComplexT(float, float);
};
ComplexT::ComplexT(float d1, float d2=1){
real = d1; img = d2;
}
void main(){
ComplexT s[ ]={ {1.1}, {3.3}, ComplexT(4.4,1.1)};
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 116
Yokedici (= Destructor) Fonksiyonlar
Yokedici ( Yokedici (= = Destructor) Fonksiyonlar Destructor) Fonksiyonlar
Yokedici fonksiyonlar, kurucu fonksiyonlar gibi o snftan bir
nesnenin yelerini yeni nesneye kopyalamakta kullanlr. Bu nedenle
parametrelerden biri ayn snftan bir nesnedir.
Yokedici fonksiyonun ad ~ ~ ile balar ve snf ad ile ayndr.
Yokedici fonksiyonlar parametre almazlar ve bir deer
dndrmezler.
Yokedici fonksiyonlar bir kere ve otomatik olarak nesne erimi
dna kldnda derleyici tarafndan arlr.
59
C++ ve NESNEYE DAYALI PROGRAMLAMA 117
class string{
int size;
char *contents;
public:
string(); // kurucu fonksiyon
string(string &); // kopyalayc kurucu fonksiyon
void set (int, char *); // An ordinary member function
void print();
~string(); // Yokedici fonksiyon
};
string ::~ string()
{
delete contents;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 118
ie Snflar
ie Snflar ie Snflar
Bir snf ye olarak baka bir snftan nesne ierebilir.
reel
sanal
constructor
print()
pay
payda
constructor
print()
rasyonelSayi
karmasikRasyonel
pay
payda
pay
payda
c
o
n
s
t
r
u
c
t
o
r
p
r
i
n
t
(
)
60
C++ ve NESNEYE DAYALI PROGRAMLAMA 119
class rasyonelSayi{ // rasyonel sayilari modelleyen sinif tanimi
int pay,payda;
public:
rasyonelSayi(int, int);
void print();
};
rasyonelSayi::rasyonelSayi(int py, int pyd) // kurucu fonksiyon
{
pay=py;
if (pyd==0) payda=1;
else payda=pyd;
}
void rasyonelSayi::print()
{
cout << pay << / << payda;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 120
class karmasikRasyonel { // rasyonel sayilar
rasyonelSayi reel,sanal ; // nesne uyeler
public:
karmasikRasyonel(int,int); // kurucu fonksiyon
void print();
};
karmasikRasyonel::karmasikRasyonel(int r,int i):real(r,1),img(i,1)
{
:
}
void karmasikRasyonel::print()
{
[Link]();
[Link]();
}
void main() {
karmasikRasyonel karmasik(2,5);
[Link]();
}
ye nesnelere balang
deerleri veriliyor
[Link]
61
C++ ve NESNEYE DAYALI PROGRAMLAMA 121
Sabit Nesneler ve const ye Fonksiyonlar
Sabit Nesneler ve Sabit Nesneler ve const const ye Fonksiyonlar ye Fonksiyonlar
const, deitirilemez nesneler tanmlamak iin kullanlr. Const ile
tanml bir nesnenin herhangi bir yesini deitirmeye altrmak
hata oluturacaktr.
const ComplexT cz(0,1); // Sabit nesne
Bazen bir snfn belirli baz yelerinin deitirilmesini nlemek
isteriz. Bu durumda ilgili ye fonksiyonun sonuna const belirteci
konur.
void print() const // sabit fonksiyon
{
cout << complex number= << real << , << img;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 122
void main() {
const ComplexT cz(0,1); // sabit nesne
ComplexT ncz(1.2,0.5) // sabit nesne degil
[Link](); // OK
[Link](); // HATA !!!
[Link](); // OK
}
class ComplexT{
float real,img;
public:
ComplexT(float, float); // kurucu fonksiyon
void print() const; // sabit fonksiyon
void reset() {real=img=0;} // sabit degil
};
void ComplexT::print() const { // sabit fonksiyon
cout << complex number= << real << , << img;
}
ComplexT::ComplexT(float r=0,float i=0){
real=r;
img=i;
}
[Link]
62
C++ ve NESNEYE DAYALI PROGRAMLAMA 123
static Snf yeleri
static static Snf yeleri Snf yeleri
Genel olarak bir snfa ait nesnelerin verileri bellekte farkl blgelerde
yer alr. Ancak baz durumlarda, belirli bir yenin ortak bir alanda tek
bir kopyasnn bulunmas isteyebiliriz. Bu durumda static anahtar
szcnden yararlanyoruz. Static tanml yeler public yada private
tanml olabilirler. Static tanml yeler o snftan hibir nesne var
olmasa bile bellekte yer alrlar. Bu durumda static yeye erim operatr
ile eriilir : A::i = 5 ; A::i = 5 ;
int i
static
char c
Object p
char c
Object q
char c
Object r
class A{
char c;
static int i;
};
void main()
{
A p,q,r;
:
}
class A{
...
public:
static SetVal(int j){i=j;}
};
C++ ve NESNEYE DAYALI PROGRAMLAMA 124
class A{
char c;
static int count; // Number of created objects (static data)
public:
static void GetCount(){return count;} // Static function to initialize number
A(){count ++; cout<< endl << "Constructor << count;}
~A(){count--; cout<< endl << "Destructor << count;}
};
int A::number=0; // Allocating memory for number
[Link]
63
C++ ve NESNEYE DAYALI PROGRAMLAMA 125
void main(){
cout<<"\n Entering 1. BLOCK............";
A a,b,c;
{
cout<<"\n Entering 2. BLOCK............";
A d,e;
cout<<"\n Exiting 2. BLOCK............";
}
cout<<"\n Exiting 1. BLOCK............";
}
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 126
Entering 1. BLOCK............
Constructor 1
Constructor 2
Constructor 3
Entering 2. BLOCK............
Constructor 4
Constructor 5
Exiting 2. BLOCK............
Destructor 5
Destructor 4
Exiting 1. BLOCK............
Destructor 3
Destructor 2
Destructor 1
64
C++ ve NESNEYE DAYALI PROGRAMLAMA 127
lev Ykleme
lev Ykleme lev Ykleme
C tip-duyarl ve -odakl bir dildir. Her operatr belirli tiplerde
operand alr.
Cde temel tiplerden ve tretilmi tiplerden yeni tipler
tretilebilir.
Tretilen tipler iin mevcut operatrleri kullanabilir miyiz ?
Cde operatrleri aldklar operand saylarna gre
Tekli Operatrler
-, +, !, ++, --, new, delete, sizeof()
kili Operatrler
+, -, *, /, %, ^, &, |, ~, ==, <, >, +=, -=, *=, /=, %=, ^=,
&=, |=, <<, >>, <<=,>>=, <=, >=, &&, ||, ->*, ->,
[], (), delete, :: , .
l operatr ?:
eklinde snflandrabiliriz.
C++ ve NESNEYE DAYALI PROGRAMLAMA 128
/* A class to define complex numbers */
class ComplexT{
float real,img;
public:
: // Member functions
ComplexT operator+(ComplexT&); // header of operator+ function
};
/* The Body of the function for operator + */
ComplexT ComplexT::operator+(ComplexT& z)
{
ComplexT result;
[Link] = real + [Link];
[Link] = img + [Link];
return result;
}
void main()
{
ComplexT z1,z2,z3;
: // Other operations
z3=z1+z2;
}
like z3 = [Link]+(z2);
[Link]
65
C++ ve NESNEYE DAYALI PROGRAMLAMA 129
lev Ykleme
lev Ykleme lev Ykleme
devam
Yerel olarak geici nesne yaratmaktan kann.
Aadaki fonksiyon daha az bellek kullanr ve daha hzldr.
Neden?
ComplexT operator+(const ComplexT&); // header of operator+ function
/* The Body of the function for operator + */
ComplexT ComplexT::operator+(const ComplexT& z)
{
float myReal,myImg ;
myReal = real + [Link];
myImg = img + [Link];
return ComplexT(myReal,myImg);
}
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 130
Atama levi (=) Ykleme
Atama levi ( Atama levi (= =) Ykleme ) Ykleme
void ComplexT::operator=(const ComplexT& z)
{
real = [Link];
img = [Link];
}
Genellikle bir snfn birka yesini kopyalamak istediimizde
atama operatrne ilev ykleriz :
66
C++ ve NESNEYE DAYALI PROGRAMLAMA 131
class string{
int size;
char *contents;
public:
void operator=(const string &); // assignment operator
: // Other methods
};
void string::operator=(const string &s)
{
size = [Link];
contents = new char[strlen([Link])];
strcpy(contents, [Link]);
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 132
Atama levi (=) Ykleme
Atama levi ( Atama levi (= =) Ykleme ) Ykleme
devam
Bir nceki rnekteki atama operatr ile
s1=s2=s3 ;
eklinde i ie atamalar yaplamaz. nk ilev yklediimiz
atama operatr ayn snftan bir nesne dndrmemektedir.
string & string::operator=(const string &s)
{
size = [Link];
contents = new char[strlen([Link])];
strcpy(contents, [Link]);
return *this;
}
[Link]
67
C++ ve NESNEYE DAYALI PROGRAMLAMA 133
Tekil levler Ykleme
Tekil levler Ykleme Tekil levler Ykleme
void ComplexT::operator++()
{
re=re+0.1;
}
void main()
{
ComplexT z(1.2, 0.5);
++z;
[Link]();
}
Tekli Operatrler : Tek bir operand alrlar
-, +, !, ++, --
Bu nedenle herhangi bir deer dndrmezler.
C++ ve NESNEYE DAYALI PROGRAMLAMA 134
Tekil levler Ykleme
Tekil levler Ykleme Tekil levler Ykleme
devam
Eer tekli operatrlerin bir deer dndrmesini istersek, o
snftan bir nesne geri dndrecek ekilde aadaki gibi prototip
fonksiyon deitirilmelidir:
ComplexT & ComplexT::operator++()
{
real=real+0.1;
return *this;
}
void main()
{
ComplexT z1(1.2, 0.5),z2;
z2= ++z1; // Prefix or postfix
[Link]();
}
[Link]
68
C++ ve NESNEYE DAYALI PROGRAMLAMA 135
Snf Yaps
Kaltm
ok ekillilik
C++ ve NESNEYE DAYALI PROGRAMLAMA 136
KALITIM (= Inheritence)
KALITIM (= Inheritence) KALITIM (= Inheritence)
C++n yazlan kodun yeniden kullanlabilir olmasn salayan
mekanizmas kaltmdr. Yeniden kullanlabilirlikten, bir snfn
alnp bir baka yazlm uygulamasnda da kullanlabilmesini
anlyoruz. Bu zellik yazlm gelitirme evrimini ksaltrken ayn
zamanda yazlmn daha grbz olmasn salayacaktr.
Tarihe :
Kopyala ve Yaptr + Uyarla + Hata Aykla,
Tekrar tekrar kullanlan fonksiyonlar iin ktphaneler olutur,
Yeni yazlm projesi
Ktphane Fonksiyonlar (Uyarla + Hata Aykla)
69
C++ ve NESNEYE DAYALI PROGRAMLAMA 137
zm :
Snf Ktphaneleri
Problemleri daha iyi modellediklerinden yeni bir proje iin
kullanlmak istenildiklerinde daha az deitirilme ihtiyac
duyarlar.
C++ bir snfn kodunu deitirmeden eklentiler yapmamza
olanak tanr. Bu kaltm yolu ile bir temel snftan yeni bir snf
tretilmesi eklinde olur. tretilen snf tretilen snf ile temel snf temel snf arasnda
is a eklinde bir hiyerarik iliki szkonusudur.
Bir temel snftan tretilen snf belirtmek iin tretilen snf
adndan sonra : : konup temel snf ad yazlr.
KALITIM
KALITIM KALITIM
C++ ve NESNEYE DAYALI PROGRAMLAMA 138
class teacher { // temel snf
public:
char *Name;
int Age,numberOfStudents;
void setName (char *new_name){Name=new_name;}
};
class principal : public teacher { // turetilmis sinif
char *schoolName;
int numberOfTeachers;
public:
void setSchool(char *s_name){schoolName=s_name;}
};
KALITIM
KALITIM KALITIM
70
C++ ve NESNEYE DAYALI PROGRAMLAMA 139
void main()
{
teacher t1;
principal p1;
[Link](" Principal 1");
[Link](" Teacher 1");
[Link](" Elementary School");
}
principal (tretilmi snf )
SchoolName
numberOfTeachers
setSchool(char *)
teacher (temel snf )
Name,
Age,
numberOfStudents
setName(char *)
principal is a is a teacher
temel snf ile tretilmi
snf arasnda is a is a ilikisi
vardr
C++ ve NESNEYE DAYALI PROGRAMLAMA 140
dikdrtgen
.
. .
nokta
ember elips
en
boy
71
C++ ve NESNEYE DAYALI PROGRAMLAMA 141
class point { // temel snf
int x,y;
public:
void setPoint(int X,int Y){x=X;y=Y;}
};
class rectangle : public point { // turetilmis sinif
int Width,Height ;
public:
void setSize(int w,int h){Width=w;Height=h}
};
class circle : public rectangle { // turetilmis sinif
public:
void setRadius(int r){Width=Height=r;}
};
C++ ve NESNEYE DAYALI PROGRAMLAMA 142
C++n yazlan kodun yeniden kullanlabilir olmasn salayan
mekanizma kaltmdr. Yeniden kullanlabilirlikten, bir snfn
alnp bir baka yazlm uygulamasnda da (aynen yada
deiikliklerle birlikte) kullanlabilmesini anlyoruz. Bu zellik
yazlm gelitirme srecini ksaltrken ayn zamanda yazlmn
daha grbz olmasn salayacaktr:
stemlerin Analizi
Sistem Analizi
Tasarm
Kodlama
Test
Bakm
72
C++ ve NESNEYE DAYALI PROGRAMLAMA 143
class teacher{ // Base class
public:
char *Name;
int Age,numberOfStudents;
void setName (char *new_name){Name=new_name;}
void print();
};
void teacher::print() // Print method of teacher class
{
cout <<"Name: "<< Name<<" Age: "<< age<< endl;
cout << "Number of Students: " <<numberOfStudents << endl;
}
Baz durumlarda, temel snftaki bir fonksiyonu, tretilmi
snfta yeniden tanmlamak gerekebilir:
Tretilmi Snfta yelerin Yeniden Tanmlanabilmesi
Tretilmi Snfta yelerin Yeniden Tanmlanabilmesi Tretilmi Snfta yelerin Yeniden Tanmlanabilmesi
C++ ve NESNEYE DAYALI PROGRAMLAMA 144
class principal : public teacher{ // Derived class
public:
char *schoolName;
int numberOfTeachers;
void setSchool(char *s_name){schoolName=s_name;}
void print(); // Print function of principal class
};
void principal::print() // Print method of principal class
{
cout <<Name: << Name<< Age: << Age<< endl;
cout << Number of Students: <<numberOfStudents << endl;
cout <<Name of the school: << schoolName << endl;
}
Bu durumda principal snf iinde tanmladmz yeni print()
fonksiyonu temel snfta tanml print() fonksiyonu zerine
yazacaktr. Eer temel snftaki print() fonksiyonuna eriilmek
istenirse :: :: operatr kullanlarak teacher::print() yazlr.
[Link]
73
C++ ve NESNEYE DAYALI PROGRAMLAMA 145
class A{
public:
int ia1,ia2;
void fa1();
int fa2(int);
};
class B: public A{
public:
float ia1; // overrides ia1
float fa1(float); // overrides fa1
};
rnek
void main(){
B b;
b.ia1=4; // B::ia1
float y=b.fa1(3.14);
// B::fa1
b.fa1();
// ERROR fa1 function in B hides the function of A
b.A::fa1(); // OK
b.A::ia1=1; // OK
}
int j=b.fa2(1);
b.ia2=3;
// A::ia2 if ia2 is public in A
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 146
Hatrlatma: Bir snf yesi (snf ierisindeki) dier tm yelere
eriebilir. O snftan bir nesne ise sadece public public ile tanml
yelere eriebilir.
Kaltm mekanizmasnda, tretilmi snf yelerinin, temel snf
yelerine eriimi nasl denetlenebilir?
Kural : tretilmi snf yeleri temel snfn
public ve protected
ile tanmlanm yelerine eriebilir.
Eriim Denetimi
Eriim Denetimi Eriim Denetimi
74
C++ ve NESNEYE DAYALI PROGRAMLAMA 147
Eriim Kendi snfndan Tretilmi snftan Dardan
eriim eriim eriim
public evet evet evet
protected evet evet hayr
private evet hayr hayr
Genel olarak, yeleri private private tanmlamak uygun
olacaktr. Bylelikle dardan bir fonksiyonun yanllkla
yenin deerini deitirmesi olasl ortadan kaldrlm
olur. Temel snf tasarlanrken olabildiince protected protected
kullanlmasndan kanlmaldr. Yeni snflar kaltm
yoluyla tretilerek geniletildike, st snflarn temel
snf yelerine eriimi (karmakl) nlenmi olur.
Bylelikle daha kararl ve gvenilir snflar
gerekletirilebilinir.
C++ ve NESNEYE DAYALI PROGRAMLAMA 148
class teacher{ // Base class
private:
char *Name;
protected:
int Age,numberOfStudents;
public:
void setName (char *new_name){Name=new_name;}
void print();
};
class principal : public teacher{ // Derived class
char *schoolName;
int numberOfTeachers;
public:
void setSchool(char *s_name){schoolName=s_name;}
void print(); // Print function of principal class
int getAge(){ return Age;} // It works because age is protected
char * get_name(){ return Name;}
};
75
C++ ve NESNEYE DAYALI PROGRAMLAMA 149
[Link]=100;
[Link](Sema Catir");
[Link](Halide Edip Adivar Lisesi");
void main()
{
teacher t1;
principal p1;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 150
Kaltm ile bir snf tretilirken, genellikle public taks kullanlr:
class Base
{ };
class Derived : public public Base {
Bu ekilde tretilen bir snfta temel snfn yelik
tanmlamalar deimez. rnein temel snfn public yeleri
ayn zamanda tretilen snfn da public yeleri olacaktr.
Public Kaltm
P Public ublic Kaltm Kaltm
76
C++ ve NESNEYE DAYALI PROGRAMLAMA 151
class Base
{ };
class Derived : private Base {
Buna private inheritance denir. Temel snfn public yeleri
tretilen snfn private yeleri olur. Bunun sonucu olarak
tretilmi snfa ait nesneler temel snfn hibir elemanna
eriemezler. Tretilen snfn yeleri temel snfn public and
protected tanml yelerine eriebilir.
private Kaltm
private private Kaltm Kaltm
C++ ve NESNEYE DAYALI PROGRAMLAMA 152
Class Base{
public:
void f();
};
class Derived : private private Base{ // All members of Base are private now
int i;
public:
Base::f(); // f() is public again
void fb1();
};
Temel snfn public tanml yelerine eriim tretilmi snfta
yeniden tanmlanabilir.
Tretilmi Snfta Eriimin Yeniden Tanmlanmas
Tretilmi Snfta Eriimin Yeniden Tanmlanmas Tretilmi Snfta Eriimin Yeniden Tanmlanmas
77
C++ ve NESNEYE DAYALI PROGRAMLAMA 153
private
public
protected
Class A
private
public
protected
Class B: public A
private
public
protected
Class C: private A
ObjB
ObjC
ObjA
yasak
C++ ve NESNEYE DAYALI PROGRAMLAMA
C++ ve NESNEYE DAYALI PROGRAMLAMA 154
Temel snfta tanml bir fonksiyon, eer ilev ykleme
yaplmam ise, otomatik olarak tretilen snf yelerinin
kullanmna aktarlr. Ancak baz zel fonksiyonlar, kaltm ile
tretilmi snfa aktarlmazlar:
lev yklenmi = operatr
lev yklenmi atama operatrnn amacn hatrlaynz !
Kurucu Fonksiyonlar
Temel snfn kurucu fonksiyonu tretilmi snfn kurucu
fonksiyonu deildir.
Yokedici Fonksiyonlar
Temel snfn yokedici fonksiyonu tretilmi snfn
yokedici fonksiyonu deildir.
Kaltm ile Aktarlamayan Fonksiyonlar
Kaltm ile Aktarlamayan Fonksiyonlar Kaltm ile Aktarlamayan Fonksiyonlar
78
C++ ve NESNEYE DAYALI PROGRAMLAMA 155
[Link]
Tretilmi snftan bir nesne yaratldnda, temel snfa ait kurucu
fonksiyon tretilmi snfa ait kurucu fonksiyondan nce arlr.
Temel snf yeleri tretilmi snfn bir alt paras olduundan st
para oluturulmadan nce alt paralara ait yelerin yaplandrlmas
zorunluluu vardr.
class teacher{ // turetilmis sinif
char *Name;
int Age,numberOfStudents;
public:
teacher(char *newName){Name=newName;} // temel sinif kurucusu
};
class principal : public teacher{ // turetilmis sinif
int numberOfTeachers;
public:
principal(char *, int ); // // turetilmis sinif kurucusu
};
Kurucu Fonksiyonlar ve Kaltm
Kurucu Fonksiyonlar ve Kaltm Kurucu Fonksiyonlar ve Kaltm
C++ ve NESNEYE DAYALI PROGRAMLAMA 156
principal::principal(char *new_name,int numOT):teacher(new_name)
{
numOfTeachers=numOT;
}
void main()
{
principal p1(Sema Catir",20);
}
Eer temel snf, parametre alan bir kurucu fonksiyona sahip ise
tretilmi snfa ait kurucu fonksiyon, temel snf kurucu
fonksiyonunu, uygun parametreler ile aracak bir kurucuya
sahip olmaldr.
[Link]
79
C++ ve NESNEYE DAYALI PROGRAMLAMA 157
Yokedici Fonksiyonlar ve Kaltm
Yokedici Fonksiyonlar ve Kaltm Yokedici Fonksiyonlar ve Kaltm
Yokedici fonksiyonlar nesnenin erimi dna kldnda otomatik
olarak arlrlar. Kaltm ile tretilmi snflarda yokedici
fonksiyonlarn arl sras kurucu fonksiyonlarn arl srasnn
tersi eklindedir.
Bu durumda ilk olarak tretilmi snfn yokedici fonksiyonu
arlacaktr.
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 158
#include <iostream.h>
class B {
public:
B() { cout << "B constructor" << endl; }
~B() { cout << "B destructor" << endl; }
};
class C : public B {
public:
C() { cout << "C constructor" << endl; }
~C() { cout << "C destructor" << endl; }
};
void main(){
cout << "Start" << endl;
C ch; // create a C object
cout << "End" << endl;
}
80
C++ ve NESNEYE DAYALI PROGRAMLAMA 159
Atama levi ve Kaltm
Atama levi ve Kaltm Atama levi ve Kaltm
Temel snfn atama ilevi tretilen snfn atama ilevi olamaz.
class string {
protected:
int size;
char *contents;
public:
string & operator=(const string &); // atama islevi
: // Other methods
};
string & string::operator=(const string &in_object) {
size = in_object.size;
contents = new char[strlen(in_object.contents)+1];
strcpy(contents, in_object.contents);
return *this;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 160
[Link]
class string2 : public string { // string2 is derived from string
int size2;
char *contents2;
public:
string2 & operator=(const string2 &); // assignment operator for string2
: // Other methods
};
/**** Assignment operator for string2 ****/
string2 & string2::operator=(const string2 &in_object) {
size = in_object.size; // inherited size
contents = new char[strlen(in_object.contents)+1]; // inherited contents
strcpy(contents, in_object.contents);
size2 = in_object.size2;
contents2 = new char[strlen(in_object.contents2)+1];
strcpy(contents2, in_object.contents2);
return *this;
}
81
C++ ve NESNEYE DAYALI PROGRAMLAMA 161
#include <iostream.h>
class A {
private:
int x;
float y;
public:
A(int i, float f) :
x(i), y(f) // initialize A
{ cout << "Constructor A" << endl; }
void display() {
cout << x << ", " << y << "; "; }
};
class B : public A {
private:
int v;
float w;
public:
B(int i1, float f1, int i2, float f2) :
A(i1, f1), // initialize A
v(i2), w(f2) // initialize B
{ cout << "Constructor B" << endl; }
void display(){
A::display();
cout << v << ", " << w << "; ";
}
};
class C : public B {
private:
int y;
float z;
public:
C(int i1,float f1, int i2,float f2,int i3,float f3) :
B(i1, f1, i2, f2), // initialize B
y(i3), z(f3) // initialize C
{ cout << "Constructor C" << endl; }
void display() {
B::display();
cout << y << ", " << z;
}
};
rnek : Snf ve Kurucu Zinciri
rnek : Snf ve rnek : Snf ve Kurucu Zinciri Kurucu Zinciri
[Link]
void main() {
C c(1, 1.1, 2, 2.2, 3, 3.3);
cout << "\nData in c = ";
[Link]();
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 162
rnek : Snf ve Kurucu Zinciri Aklama
rnek : Snf ve rnek : Snf ve Kurucu Zinciri Kurucu Zinciri Aklama Aklama
C snf B snfndan ve B snf da A snfndan tretilmitir. Her
snf kendi ve alt snflardaki kurucu fonksiyonlarna uygun sayda
parametre almakta ve aktarmaktadr: A snf kurucu fonksiyonu
iki, B snf kurucu fonksiyonu drt (ikisi A snf iin) ve C snf
kurucu fonksiyonu (A ve B snflar kurucular iin ikier
parametre) alt parametre almaktadr.
main() fonksiyonunda C snfndan c adnda bir nesne tanmlayp 6
adet balang deeri verdik. Bylelikle tm alt snflara uygun
balang deeri verildi.
C(int i1, float f1,int i2, float f2, int i3, float f3) :
A(i1, f1), // error: can't initialize A
y(i3), z(f3) // initialize C
{ }
82
C++ ve NESNEYE DAYALI PROGRAMLAMA 163
class A{
int i1,i2;
A(int new1, int new2): i1(new1),i2(new2) {
...
}
};
int ve float gibi basit veri tipine sahip snf yelerine aadaki
gibi balang deeri verilebilir :
Ancak bu bir kaltm uygulamas deildir. Ancak bu bir kaltm uygulamas deildir.
C++ ve NESNEYE DAYALI PROGRAMLAMA 164
oklu Kaltm
bir snfn birden fazla temel snftan tretilmesi
oklu Kaltm oklu Kaltm
bir snfn birden fazla temel snftan tretilmesi
class Base1{ // Base 1
public:
int a;
void fa1();
char *fa2(int);
};
class Base2{ // Base 2
public:
int a;
char *fa2(int, char);
int fc();
};
class Deriv : public Base1 , public Base2{
public:
int a;
float fa1(float);
int fb1(int);
};
Base1 Base2
Deriv
+
+
[Link]
void main()
{
Deriv d;
d.a=4; //Deriv::a
float y=d.fa1(3.14); //Deriv::fa1
int i=[Link](); // Base2::fc
}
char * c=d.fa2(1);
Atamas geerli deildir.
Kaltm ile yeniden tanmlanan
fonksiyonlara ilev yklenemez.
Geerli kullanm :
char * c=d.Base1::fa2(1);
yada
char * c=d.Base2::fa2(1,"Hello");
83
C++ ve NESNEYE DAYALI PROGRAMLAMA 165
Tekrarl Kaltm
Tekrarl Kaltm Tekrarl Kaltm
class Gparent
{ };
class Mother : public Gparent
{ };
class Father : public Gparent
{ };
class Child : public Mother, public Father
{ };
Child
Gparent
Mother Father
Hem Mother hem de Father snflarnn Gparent
snfndan tretildiine dikkat ediniz. Child snf
ise oklu kaltm ile Father ve Mother
snflarndan tretilmitir.
Bu durumda Gparent snf hem Mother ve hem
de Father snflarnda ortak olduundan Child
snf iki adet Gparent alt snfna sahiptir biri
Father dieri Mother snflarndan.
C++ ve NESNEYE DAYALI PROGRAMLAMA 166
class Gparent
{
protected:
int gdata;
};
class Child : public Mother, public Father
{
public:
void Cfunc() {
int temp = gdata; // error: ambiguous
}
};
Ayrca Gparent snfnda aada verildii gibi bir int tipinde yeye
sahip olsun.
Derleyici, Father snfndan gelen gdatay m? yoksa Mother
snfndan gelen gdatay kullanmal? belirsizlii nedeni ile
hata verecektir.
84
C++ ve NESNEYE DAYALI PROGRAMLAMA 167
zm : Sanal Snflar
zm : Sanal Snflar zm : Sanal Snflar
Bu problem virtual anahtar szc kullanlarak zlebilir.
class Gparent
{ };
class Mother : virtual public Gparent
{ };
class Father : virtual public Gparent
{ };
class Child : public Mother, public Father
{ };
virtual anahtar szc derleyiciye kaltm ile alt snflardan tretilen alt
nesnelerden sadece birinin kullanmasn syler. Ancak bu zmde burada
detayl olarak duramayacamz baz karmak durumlarda yeni belirsizlikler
getirebilmektedir.
Genel olarak oklu kaltmdan kanmalsnz. Ancak C++da deneyimli iseniz,
oklu kaltmn gerekli olduu durumlarda kullanmanz zm
kolaylatracaktr.
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 168
class Base
{
public:
int a,b,c;
};
class Derived : public Base
{
public:
int b;
};
class Derived2 : public Derived
{
public:
int c;
};
Base Base
Drived Drived
Derived2 Derived2
85
C++ ve NESNEYE DAYALI PROGRAMLAMA 169
class A {
...
};
class B {
...
};
class C {
...
};
class D : public A, public B, private C {
...
};
A A
B B
D D
C C
C++ ve NESNEYE DAYALI PROGRAMLAMA 170
class L {
public:
int next;
};
class A : public L {
...
};
class B : public L {
...
};
class C : public A, public B {
void f() ;
...
};
A B
C
L L
86
C++ ve NESNEYE DAYALI PROGRAMLAMA 171
class L {
public:
int next;
};
class A : virtual public L {
...
};
class B : virtual public L {
...
};
class C : public A, public B {
...
};
A B
C
L
C++ ve NESNEYE DAYALI PROGRAMLAMA 172
class B {
...
};
class X : virtual public B {
...
};
class Y : virtual public B {
...
};
class Z : public B {
...
};
class AA : public X, public Y , public Z {
...
};
X Y
AA
B
Z
B
87
C++ ve NESNEYE DAYALI PROGRAMLAMA 173
Snf Yaps
Kaltm
Nesne aretileri
ok ekillilik
C++ ve NESNEYE DAYALI PROGRAMLAMA 174
aretiler veri deil verinin yerleik bulunduu bellek gznn
adresini tarlar. aretiler basit tipte deikenlere iaret edebildikleri
gibi bir nesneye de iaret edebilirler. aretiler kullanlmadan nce
uygun balang deeri atanmaldr:
new new operatr
letim sisteminden uygun miktarda bellek alan alr. Dndrd
deer bu alann balang adresidir. Eer ilem baarsz olursa 0
(NULL) dndrr.
Nesne iaretilerinde new kullanldnda yukardakine ek olarak
nesnenin kurucu fonksiyonu altrlr. Byle nesne yaratlrken
balang deerleri atanm olur.
Nesne aretileri
Nesne aretileri Nesne aretileri
88
C++ ve NESNEYE DAYALI PROGRAMLAMA 175
delete delete operatr
Bellein verimli ve etkin kullanm iin, new operatrnn
kullanmna karlk olarak bellek alan kullanm bittiinde iletim
sistemine delete operatr ile geri verilmelidir.
new ile aadaki biimde bir nesne dizisi iin bellek alndnda
int * ptr = new int[10];
delete ile
delete [ ] ptr;
eklinde iletim siteminde geri verilmelidir. areti nndeki
[] kullanlmaz ise sadece dizinin ilk eleman iin bellek alan
geri verilir.
Nesne aretileri
Nesne aretileri Nesne aretileri
devam
C++ ve NESNEYE DAYALI PROGRAMLAMA 176
[Link]
class person // class of persons
{
char *name; // person's name
public:
person(); //Default Constructor
void setName(char *); // set the name
void printName() // print the name
{
cout << "Name is:" << name<<endl;
}
~person()
{ cout << "Destructor" << endl;
delete name;}
};
person::person()
{
cout << "Constructor" << endl;
name = new char;
name = '\0';
}
void person::setName(char *n)
{
delete name;
name = new char[strlen(n)];
strcpy(name, n);
}
void main()
{
person* persPtr = new person[3];
persPtr->setName("Person1");
(persPtr+1)->setName("Person2");
(persPtr+2)->setName("Person3");
persPtr->printName();
(persPtr+1)->printName();
(persPtr+2)->printName();
delete [ ] persPtr;
} // end main()
89
C++ ve NESNEYE DAYALI PROGRAMLAMA 177
Nesne Balantl Listeleri
Nesne Balantl Listeleri Nesne Balantl Listeleri
Bir snf kendi tipinden bir nesneye iareti ierebilir. Bu
iareti kullanlarak bir nesne zinciri (balantl liste) kurulabilir.
class teacher{
friend class teacher_list;
char *name;
int age,numOfStudents;
teacher * next; // Pointer to next object of teacher
public:
teacher(char *, int, int); // Constructor
void print();
char *getName(){return name;}
~teacher() // Destructor
{
cout<<" Destructor of teacher" << endl;
delete name;
}
};
/* linked list for teachers */
class teacher_list{
teacher *head;
public:
teacher_list(){head=0;}
char append(char *,int,int);
char del(char *);
void print();
};
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 178
Eer bir snf temel bir snftan tretilmi ise, tretilmi snftan bir iaretiye
herhangi bir tip dnm gerekmeksizin temel snftan bir iareti
[Link] snfn iaretisi tretilmi snfa iareti olabilir. Tersi bir
dnm, tip dnm gerektirir.
rnein, teacher nesnesine bir iareti teacher ve principal nesnelerine iaret
edebilir. principal ile teacher arasnda is a ilikisi vardr : principal is a
teacher. Ancak tersi her zaman doru deildir : her teacher bir principal
olmayabilir.
aretiler ve Kaltm
aretiler ve Kaltm aretiler ve Kaltm
class Base Base{
};
class Derived Derived : public Base Base {
};
Derived Derived d,*dp;
Base Base *bp=&d; // implicit conversion
dp=bp; // error Base is not Derived
dp = (Derived *)bp; // explicit conversion
90
C++ ve NESNEYE DAYALI PROGRAMLAMA 179
Eer bir snf kaltm ile private olarak temel snftan tretilirse,
bu durumda tip dnm yaplamaz. nk temel snfn
public yeleri temel snfa ait iaretiler tarafndan eriilebilir.
Ancak tretilmi snftan nesneler yada iaretiler temel snf
yelerine eriemezler.
class class Base Base{
int m1;
public:
int m2;
};
class class Derived Derived : private private Base Base { // m2 is not a public member of Derived
};
Derived d;
d.m2=5; // error m2 is private member of Derived
base *bp=&d; // error private base
bp->m2=5; // ok
bp = (base*)&d; // ok: explicit conversion
bp->m2=5; // ok
C++ ve NESNEYE DAYALI PROGRAMLAMA 180
aretiler ve kaltm kullanlarak, heterojen balantl listeler
oluturulabilir. Temel snfa iaret eden nesnelerden oluan liste,
bu temel snftan tretilmi tm snflara ait nesneler ierebilir.
Heterojen listeleri daha sonra ok ekillilik konusunda tekrar
inceleyeceiz.
rnek rnek: retmenler ve mdrler listesi
next
teacher t3
next
teacher t2
next
principal p2
next
principal p1
next
teacher t1
head
insert()
delete()
List my_list
0
[Link]
91
C++ ve NESNEYE DAYALI PROGRAMLAMA 181
UYGULAMA UYGULAMA
UYGULAMA
C++ ve NESNEYE DAYALI PROGRAMLAMA 182
3
Snf Yaps
Kaltm
ok ekillilik
Nesneye dayal programlamann temel kavram :
1. Snflar,
2. Kaltm,
3. ok ekillilik ok ekillilik (C++da sanal fonksiyonlar sanal fonksiyonlar ile salanr)
92
C++ ve NESNEYE DAYALI PROGRAMLAMA 183
OK EKLLLK (=POLYMORPHISM)
OK EKLLLK (=POLYMORPHISM) OK EKLLLK (=POLYMORPHISM)
Gerek hayattaki nesneler farkl snflardan olsalar da, yada farkl
davranlar gerekletirseler de, baz ortak ilevlere sahip
olabilmektedirler. rnek olarak kare kare, daire daire, gen gen snflarndan
nesneleri ele alalm:
Tm bu nesnelere Alan Hesapla mesajn gndermi olalm.
Farkl tipte nesneler (kare kare, daire daire, gen gen) farkl alan hesabna
sahiptir. Ancak farkl tipte nesnelere farkl mesaj gndermeye
gerek yoktur. Bu ilem iin tek bir tr mesaj ( Area() Area() ) tm
nesnelerde iin almaldr. nk her bir tip nesne kendi
snfndan nesnelerin alann nasl hesaplayacan bilmektedir:
kare kareArea Area() ;
daire daireArea Area();
gen genArea Area();
C++ ve NESNEYE DAYALI PROGRAMLAMA 184
OK EKLLLK
OK EKLLLK OK EKLLLK
devam
Bu biraz, fonksiyona ilev yklemeyi artrmaktadr. Ancak ok
ekillilik daha gl ve farkl bir mekanizma sunmaktadr. nemli
fark, hangi fonksiyonun arlacana ne zaman karar verildiinde
ortaya kmaktadr.
Fonksiyon yklemede bu karar, derleyici tarafndan derleme
aamasnda verilirken, ok ekillikte bu karar yrtme zamannda
verilmektedir.
ok ekillilik, genellikle birbirleri ile kaltmla ilikili snflar
arasnda gerekleir. C++da ok ekilliin anlam, bir ye
fonksiyona yaplan arnn, farkl nesnelerde, nesnenin tipine bal
olarak farkl fonksiyonlarn arlmasna neden olmasdr.
Area() Area() ilevi farkl tipte nesnelerde farkl biimler aldndan
ok ekillik ok ekillik gsteren bir metodtur.
93
C++ ve NESNEYE DAYALI PROGRAMLAMA 185
class Square Square { // Temel sinif
protected:
double edge;
public:
Square(double e):edge(e){ } // temel sinif kurucusu
double Area Area(){ return( edge * edge ) ; }
};
class Cube Cube : public Square Square { // Turetilmis sinif
public:
Cube(double e):Square(e){} // Turetilmis sinif kurucusu
double Area Area(){ return( 6.0 * edge * edge ) ; }
};
Normal Snf yelerine
ok ekillilik Mekanizmas Kullanlmadan
aretiler ile Eriim
Normal Snf yelerine Normal Snf yelerine
ok ekillilik Mekanizmas Kullanlmadan ok ekillilik Mekanizmas Kullanlmadan
aretiler ile Eriim aretiler ile Eriim
C++ ve NESNEYE DAYALI PROGRAMLAMA 186
void main(){
Square S(2.0) ;
Cube C(8.0) ;
Square *ptr ;
char c ;
cout << Square or Cube"; cin >> c ;
if (c==s') ptr=&S ;
else ptr=&C ;
ptrArea(); // which Area ???
}
Cube snf Square snfndan tretilmitir. Her iki snfta Area() ye
mesajn iermektedir. main() fonksiyonunda, Square ve Cube snflarndan
birer nesne ve Square snfna bir iareti tanmlanmtr. Ardndan
tretilmi snftan nesnenin adresi temel snfa iaret eden iaretiye
atanmtr:
ptr = &C;
Bu geerli bir atamadr
[Link]
94
C++ ve NESNEYE DAYALI PROGRAMLAMA 187
Aadaki satr yrtldnde
ptrArea();
Square:: Area() fonksiyonu mu?
yoksa
Cube::Area() fonksiyonu mu?
arlr.
C++ ve NESNEYE DAYALI PROGRAMLAMA 188
imdi programda tek bir deiiklik yapalm: temel snftaki
Area Area() fonksiyonunun nne virtual virtual anahtar szcn koyalm.
aretiler ile Eriilen Virtual ye Fonksiyonlar
aretiler ile Eriilen aretiler ile Eriilen Virtual Virtual ye Fonksiyonlar ye Fonksiyonlar
class Square Square { // Temel sinif
protected:
double edge;
public:
Square(double e):edge(e){ } // temel sinif kurucusu
virtual virtual double Area Area(){ return( edge * edge ) ; }
};
class Cube Cube : public Square Square { // Turetilmis sinif
public:
Cube(double e):Square(e){} // Turetilmis sinif kurucusu
double Area Area(){ return( 6.0 * edge * edge ) ; }
};
95
C++ ve NESNEYE DAYALI PROGRAMLAMA 189
void main(){
Square S(2.0) ;
Cube C(8.0) ;
Square *ptr ;
char c ;
cout << Square or Cube"; cin >> c ;
if (c==s') ptr=&S ;
else ptr=&C ;
ptrArea();
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 190
imdi ptrnin ieriine gre farkl fonksiyonlar arlacaktr. Fonksiyonlar
ptrnin tipine gre deil, ieriine gre arlmaktr. Bu ekilde ok ekillilik
salanr. virtual anahtar szc, Area() fonksiyonunun ok ekilli olmasn
salamaktadr.
Peki derleyici hangi fonksiyonu aracan derleme zamannda nasl
biliyor? virtual anahtar szcn kullanmadmz ilk rnekte bir sorun yoktu:
ptrArea(); her zaman temel snftaki Area() fonksiyonu altrlr. Ama ikinci
rnekte, derleyici ptr iaretisinin hangi tipten bir snfn nesnesine iaret ettiini
bilmektedir. ptr yrtme zamannda Square snfndan yada Cube snfndan bir
nesneye iaret edebilir. Bu durumda hangi Area() altrlr? Derleyici derleme
esnasnda bu karar veremeyeceinden, yrtme zamannda bu karar verecek
ekilde kodu dzenler.
Yrtme zamannda, fonksiyon ars olutuunda, derleyicinin yerletirdii
bir kod, ptr nesne iaretisinin hangi tipten bir nesneye iaret ettiini alglar ve
ilgili fonksiyonu arr: Square::Area() yada Cube::Area().
Buna late binding yada dynamic binding ad verilmektedir. Late binding bir
miktar ek ilem yk getirmektedir (yaklak %10 gibi). Ama bunun
karlnda yazdmz programa byk bir esneklik ve yetenek
kazandrmaktadr.
96
C++ ve NESNEYE DAYALI PROGRAMLAMA 191
Virtual tanmlamas iermeyen bir snfa ait nesne sadece ye
alanalar bellekte yerleik bulunur. lgili nesne iin bir ye
fonksiyona ar yapldnda, derleyici nesnenin adresini fonksiyona
parametre olarak aktarr. Bu adresin this deikeninde sakl
bulunduunu hatrlaynz. Derleyici, fonksiyonunun formal
parametrelerine ek olarak (programcya gizli bir biimde) this
iaretisini ekler. Bu parametre her ilgili fonksiyon arsnda
derleyici tarafndan aktarlacaktr; this iaretisi nesnenin yeleri
ile fonksiyonlar arasndaki yegane balanty oluturmaktadr.
virtual tanml fonksiyonlar ise biraz daha karmak bir davran
gstermektedir. Tretilmi snfta tanmlanan her virtual fonksiyon
iin derleyici, Virtual Table ad verilen bir dizi (tablo) oluturur.
Square ve Cube snflarnn her biri Virtual Table dizisine sahiptir.
Bu dizilerde, o snftaki her bir virtual fonksiyon iin bir kayt
bulunur (tutulur).
C++ ve NESNEYE DAYALI PROGRAMLAMA 192
. .
. .
. .
. .
. .
. .
s1. [Link] this
virtual Area
Square
virtual Area
Cube
kaltm kaltm
Square s1(1),s2(4),s3(3);
Cube c1(2),c2(7) ;
Cube c3(8),c4(8) ;
Square *p ;
...
p = &c2 ;
...
p->Area() ;
...
p = &s3 ;
...
p->Area() ;
s3. [Link] this
c1. [Link] this
c4. [Link] this
97
C++ ve NESNEYE DAYALI PROGRAMLAMA 193
Bu rnekte, Square yada Cube snfndan bir
nesnenin virtual tanml fonksiyonuna bir ar
yapldnda, uygun ye fonksiyonunun arlmas
iin gerekli ilemleri derleme aamasnda
derleyici yerine, derleyicinin rettii bir kod
yrtme zamannda gerekletirmektedir.
retilen bu kod, nesnenin virtual tablosunu
tarayarak, uygun ye fonksiyona eriimi
salamaktadr.
C++ ve NESNEYE DAYALI PROGRAMLAMA 194
Bunu Nesneler ile Denemeyin !
Bunu Nesneler ile Denemeyin ! Bunu Nesneler ile Denemeyin !
Sanal fonksiyon mekanizmas sadece nesne iaretileri ile
kullanmda alr.
void main()
{
Square S(4);
Cube C(8);
[Link]();
[Link]();
}
98
C++ ve NESNEYE DAYALI PROGRAMLAMA 195
class Square Square { // Temel sinif
protected:
double edge;
public:
Square(double e):edge(e){ } // temel sinif kurucusu
virtual virtual double Area Area(){ return( edge * edge ) ; }
};
class Cube Cube : public Square Square { // Turetilmis sinif
public:
Cube(double e):Square(e){} // Turetilmis sinif kurucusu
double Area Area(){ return( 6.0 * Square::Area() Square::Area() ) ; }
};
Uyar
Burada Square::Area() Square::Area() virtual deil
C++ ve NESNEYE DAYALI PROGRAMLAMA 196
Sanal fonksiyonlarn en ok kullanm alan bulduu uygulama
balantl nesne liste yaplardr:
Nesne Balantl Listesi ve ok ekillilik
Nesne Balantl Listesi ve ok ekillilik
class Square Square { // Temel sinif
protected:
double edge;
public:
Square(double e):edge(e){ } // temel sinif kurucusu
virtual virtual double Area Area(){ return( edge * edge ) ; }
Sqaure *next ;
};
class Cube Cube : public Square Square { // Turetilmis sinif
public:
Cube(double e):Square(e){} // Turetilmis sinif kurucusu
double Area Area(){ return( 6.0 * edge * edge ) ; }
};
99
C++ ve NESNEYE DAYALI PROGRAMLAMA 197
void main(){
Cube c1(50);
Square s1(40);
Cube c2(23);
Square s2(78);
Square *listPtr; // Pointer of the linked list
/*** Construction of the list ***/
listPtr=&c1;
[Link]=&s1;
[Link]=&c2;
[Link]=&s2;
[Link]=0L;
/*** Printing all elements of the list ***/
while (listPtr){
cout << listPtr->Area() << endl ;
listPtr=listPtr->next;
}
}
[Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 198
To write polymorphic functions wee need to have derived classes. But sometimes we
dont need to create any base class objects, but only derived class objects. The base
class exists only as a starting point for deriving other classes. This kind of base classes
we can call an abstract class, which means that no actual objects will be created from
it. Abstract classes arise in many situations. A factory can make a sports car or a truck
or an ambulance, but it cant make a generic vehicle. The factory must know the details
about what kind of vehicle to make before it can actually make one. Similarly, youll
see sparrows, wrens, and robins flying around, but you wont see any generic birds.
Actually, a class is an abstract class only in the eyes of humans. The compiler is
ignorant of our decision to make it an abstract class.
Abstract Classes Abstract Classes
It would be nice if, having decided to create an abstract base class, I could instruct the
compiler to actively prevent any class user from ever making an object of that class.
This would give me more freedom in designing the base class because I wouldnt need
to plan for actual objects of the class, but only for data and functions that would be
used by derived classes. There is a way to tell the compiler that a class is abstract: You
define at least one pure virtual function in the class.
A pure virtual function is a virtual function with no body. The body of the virtual
function in the base class is removed, and the notation =0 is added to the function
declaration.
Pure Virtual Functions Pure Virtual Functions
100
C++ ve NESNEYE DAYALI PROGRAMLAMA 199
rnek
class generic_shape{ // Abstract base class
protected:
int x,y;
public:
generic_shape(int x_in,int y_in){ x=x_in; y=y_in;} // Constructor
virtual void draw()=0; // pure virtual function
};
class Line:public generic_shape{ // Line class
protected:
int x2,y2; // End coordinates of line
public:
Line(int x_in,int y_in,int x2_in,int y2_in):generic_shape(x_in,y_in)
{
x2=x2_in;
y2=y2_in;
}
void draw(){ line(x,y,x2,y2); } // virtual draw function
};
C++ ve NESNEYE DAYALI PROGRAMLAMA 200
class Rectangle:public Line{ // Rectangle class
public:
Rectangle(int x_in,int y_in,int x2_in,int y2_in):Line(x_in,y_in,x2_in,y2_in){}
void draw(){ rectangle(x,y,x2,y2); } // virtual draw
};
class Circle:public generic_shape{ // Circle class
protected:
int radius;
public:
Circle(int x_cen,int y_cen,int r):generic_shape(x_cen,y_cen)
{
radius=r;
}
void draw() { circle(x,y, radius); } // virtual draw
};
/* A function to draw different shapes ***/
void show(generic_shape &shape)
{ // Which draw function will be called?
[Link](); // It 's unknown at compile-time
}
101
C++ ve NESNEYE DAYALI PROGRAMLAMA 201 [Link]
void main()
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "\\tc\\bgi"); //To graphics mode
Line Line1(1,1,100,250);
Circle Circle1(100,100,20);
Rectangle Rectangle1(30,50,250,140);
Circle Circle2(300,170,50);
show(Circle1);
getch();
show(Line1);
getch();
show(Circle2);
getch();
show(Rectangle1);
getch();
closegraph();
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 202
Kurucu Fonksiyonlar Sanal olabilir mi?
Sanal Fonksiyonlar ve Kurucu Fonksiyonlar
Sanal Fonksiyonlar ve Kurucu Fonksiyonlar
Hayr.
Bir nesne yaratldnda, derleyici bu nesnenin hangi
snftan olduunu bilmektedir. Bu nedenle, sanal
kurucu fonksiyonlara ihtiya yoktur.
102
C++ ve NESNEYE DAYALI PROGRAMLAMA 203
Sanal Yokedici Fonksiyonlar
Sanal Yokedici Fonksiyonlar
class Base {
public:
~Base() { cout << "\nBase destructor"; }
};
class Derived : public Base {
public:
~Derv() { cout << "\nDerived destructor"; }
};
void main(){
Base* pb = new Derived;
delete pb;
cout << endl << "Program terminates. << endl ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 204
class Base {
public:
virtual virtual ~Base() { cout << "\nBase destructor"; }
};
class Derived : public Base {
public:
~Derv() { cout << "\nDerived destructor"; }
};
void main(){
Base* pb = new Derived;
delete pb;
cout << endl << "Program terminates. << endl ;
}
103
C++ ve NESNEYE DAYALI PROGRAMLAMA 205
4
Snf Yaps
Kaltm
ok ekillilik
Templates
C++ ve NESNEYE DAYALI PROGRAMLAMA 206
Parametrik ok ekillilik Nedir ?
Parametrik ok ekillilik Nedir ? Parametrik ok ekillilik Nedir ?
Snflardaki fonksiyonlarn gvdeleri incelendiinde, ou zaman
yaplan ilemler, zerinde ilem yaplan verinin tipinden
bamszdr. Bu durumda fonksiyonun gvdesi, verinin tipi
cinsinden, parametrik olarak ifade edilebilir:
int int abs(int int n) {
return (n<0) ? -n : n;
}
float float abs(float float n) {
return (n<0) ? -n : n;
}
long long abs(long long n) {
return (n<0) ? -n : n;
}
104
C++ ve NESNEYE DAYALI PROGRAMLAMA 207
C C
Her tip iin farkl adlarda fonksiyonlar.
rnek mutlak deer fonksiyonlar:
abs(), fabs(), fabsl(), labs(), cabs(), ...
C C++
Fonksiyonlara ilev ykleme bir zm olabilir mi?
lev yklenen fonksiyonlarn gvdeleri deimiyor !
Gvdeler tekrar ediliyor Hata !
zm zm
Tipi parametre kabul eden bir yap : Template
C++ ve NESNEYE DAYALI PROGRAMLAMA 208
#include <iostream.h>
template template <class class T T>
T T abs(T T n) {
return (n < 0) ? -n : n;
}
void main()
{
int int1 = 5;
int int2 = -6;
long lon1 = 70000L;
long lon2 = -80000L;
double dub1 = 9.95;
double dub2 = -10.15;
// calls instantiate functions
cout << "abs(" << int1 << ")=" << abs(int1) << endl; // abs(int)
cout << "abs(" << int2 << ")=" << abs(int2) << endl; // abs(int)
cout << "abs(" << lon1 << ")=" << abs(lon1) << endl; // abs(long)
cout << "abs(" << lon2 << ")=" << abs(lon2) << endl; // abs(long)
cout << "abs(" << dub1 << ")=" << abs(dub1) << endl; // abs(double)
cout << "abs(" << dub2 << ")=" << abs(dub2) << endl; // abs(double)
}
105
C++ ve NESNEYE DAYALI PROGRAMLAMA 209
template template <class T T>
void printArray printArray(T T *array,const int size){
for(int i=0;i < size;i++)
cout << array[i] << " " ;
cout << endl ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 210
main() {
int a a[3]={1,2,3} ;
double b b[5]={1.1,2.2,3.3,4.4,5.5} ;
char c c[7]={a, b, c, d, e , f, g} ;
printArray printArray(a a,3) ;
printArray printArray(b b,5) ;
printArray printArray(c c,7) ;
return 0 ;
}
106
C++ ve NESNEYE DAYALI PROGRAMLAMA 211
void printArray printArray(int *array,cont int size){
for(int i=0;i < size;i++)
cout << array[i] << " " ;
cout << endl ;
}
void printArray printArray(char *array,cont int size){
for(int i=0;i < size;i++)
cout << array[i] << "" ;
cout << endl ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 212
templatein leyii
template templatein leyii in leyii
Gerekte derleyici template ile verilmi fonksiyon gvdesi
iin herhangi bir kod retmez. nk template ile baz
verilerin tipi parametrik olarak ifade edilmitir. Verinin tipi
ancak bu fonksiyona ilikin bir ar olduunda ortaya
kacaktr. Derleyici her farkl tip iin yeni bir fonksiyon
oluturacaktr. template yeni fonksiyonun verinin tipine
bal olarak nasl oluturulacan tanmlamaktadr.
cout << "abs(" << int << ")=" << abs(int1 int1);
int int int1 int1 = 5;
107
C++ ve NESNEYE DAYALI PROGRAMLAMA 213
program ister template yaps ile oluturalm ister de
template yaps olmakszn oluturalm, programn bellekte
kaplayaca alan deimeyecektir. Deien, kaynak kodun
boyu olacaktr. template yaps kullanlarak oluturulan
programn kaynak kodu, daha anlalr ve hata denetimi
daha yksek olacaktr. nk template yaps
kullanldnda deiiklik sadece tek bir fonksiyon
gvdesinde yaplacaktr.
C++ ve NESNEYE DAYALI PROGRAMLAMA 214
template Parametresi bir Nesne Olabilir
template Parametresi bir Nesne Olabilir template Parametresi bir Nesne Olabilir
class ComplexT{ /* A class to define complex numbers */
float re,im;
public:
: // other member functions
bool operator>(const ComplexT&) const ; // header of operator> function
};
/* The Body of the function for operator + */
bool ComplexT::operator>(const ComplexT& z) const
{
float f1 = re * re + im * im;
float f2 = [Link] * [Link] + [Link] * [Link];
if (f1 > f2) return true;
else return false;
}
108
C++ ve NESNEYE DAYALI PROGRAMLAMA 215
// template function
template <class type type>
const type type & MAX MAX(const type type &v1, const type type & v2)
{
if (v1 > v2) return v1;
else return v2;
}
void main()
{
int i1=5, i2= -3;
char c1='D', c2='N';
float f1=3.05, f2=12.47;
ComplexT z1(1.4,0.6), z2(4.6,-3.8);
cout << MAX MAX(i1,i2) << endl;
cout << MAX MAX(c1,c2) << endl;
cout << MAX MAX(f1,f2) << endl;
cout << MAX MAX(z1,z2) << endl;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 216
// function returns index number of item, or -1 if not found template
template template <class class atype atype>
int find(const atype atype *array, atype atype value, int size) {
for(int j=0; j<size; j++)
if(array[j]==value) return j;
return -1;
}
char char chrArr[] = {'a', 'c', 'f', 's', 'u', 'z'}; // array
char char ch = 'f'; // value to find
int int intArr[] = {1, 3, 5, 9, 11, 13};
int int in = 6;
double double dubArr[] = {1.0, 3.0, 5.0, 9.0, 11.0, 13.0};
double double db = 4.0;
oklu template Parametreli Argmanlar
oklu template Parametreli Argmanlar oklu template Parametreli Argmanlar
109
C++ ve NESNEYE DAYALI PROGRAMLAMA 217
void main()
{
cout << "\n 'f' in chrArray: index=" << find(chrArr, ch, 6);
cout << "\n 6 in intArray: index=" << find(intArr, in, 6);
cout << "\n 4 in dubArray: index=" << find(dubArr, db, 6);
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 218
template mzalar
template mzalar template mzalar
template template <class class T T>
void swap(T T& x, T T& y) {
T T temp ;
temp = x ;
x = y ;
y = temp ;
}
char char str1[100], str2[100] ;
int int i,j ;
complex complex c1,c2;
swap( i , j ) ;
swap( c1 , c2 ) ;
swap( str1[50] , str2[50] ) ;
swap( i , str[25] ) ;
swap( str1 , str2 ) ;
110
C++ ve NESNEYE DAYALI PROGRAMLAMA 219
oklu template Parametreli Yaplar
oklu template Parametreli Yaplar oklu template Parametreli Yaplar
Template parametre says birden fazla olabilir:
template <class atype, class btype>
btype find(const atype* array, atype value, btype size) {
for(btype j=0; j<size; j++) // note use of btype
if(array[j]==value) return j;
return (btype)-1;
}
Bu durumda, derleyici sadece farkl dizi tipleri iin deil ayn
zamanda aranan elemann farkl tipte olmas durumunda da farkl bir
kod retecektir:
short int result,si=100;
int invalue=5;
result = find(intArr, invalue,si) ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 220
class Stack {
int st[MAX]; // array of ints
int top; // index number of top of stack
public:
Stack(); // constructor
void push(int var); // takes int as argument
int pop(); // returns int value
};
class LongStack {
long st[MAX]; // array of longs
int top; // index number of top of stack
public:
LongStack(); // constructor
void push(long var); // takes long as argument
long pop(); // returns long value
};
Snf Template Yaps
Snf Template Yaps Snf Template Yaps
111
C++ ve NESNEYE DAYALI PROGRAMLAMA 221
template <class Type>
class Stack{
enum {MAX=100};
Type st[MAX]; // stack: array of any type
int top; // number of top of stack
public:
Stack(){top = 0;} // constructor
void push(Type ); // put number on stack
Type pop(); // take number off stack
};
template<class Type>
void Stack<Type>::push(Type var) // put number on stack
{
if(top > MAX-1) // if stack full,
throw "Stack is full!"; // throw exception
st[top++] = var;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 222
template<class Type>
Type Stack<Type>::pop() { // take number off stack
if(top <= 0) // if stack empty,
throw "Stack is empty!"; // throw exception
return st[--top];
}
template<class Type>
Type Stack<Type>::pop() { // take number off stack
if(top <= 0) // if stack empty,
throw "Stack is empty!"; // throw exception
return st[--top];
}
// s2 is object of class Stack<long>
Stack<long> s2;
// push 2 longs, pop 2 longs
try{
[Link](123123123L);
[Link](234234234L);
cout << "1: " << [Link]() << endl;
cout << "2: " << [Link]() << endl;
}
// exception handler
catch(const char * msg) {
cout << msg << endl;
}
} // End of program
void main()
{
// s1 is object of class Stack<float>
Stack<float> s1;
// push 2 floats, pop 2 floats
try{
[Link](1111.1);
[Link](2222.2);
cout << "1: " << [Link]() << endl;
cout << "2: " << [Link]() << endl;
}
// exception handler
catch(const char * msg) {
cout << msg << endl;
}
112
C++ ve NESNEYE DAYALI PROGRAMLAMA 223
5
Snf Yaps
Kaltm
ok ekillilik
Templates
STL Ktphanesi ve Generic Programming
(Standard Template Library)
C++ ve NESNEYE DAYALI PROGRAMLAMA 224
Nesneye dayal programlamada, verinin birincil neme sahip
programlama birimi olduunu belirtmitik. Veri, fiziksel yada
soyut bir ok bykl modelleyebilir. Bu model olduka
basit yada karmak olabilir. Her nasl olursa olsun, veri
mutlaka bellekte saklanmaktadr ve veriye benzer biimlerde
eriilmektedir. C++, olduka karmak veri tiplerini ve
yaplarn oluturmamza olanak salayan mekanizmalara
sahiptir. Genel olarak, programlarn, bu veri yaplarna belirli
baz biimlerde eritiini biliyoruz:
array, list, stack, queue, vector, map, ...
STL ktphanesi verinin bellekteki organizasyonuna,
eriimine ve ilenmesine ynelik eitli yntemler
sunmaktadr. Bu blmde bu yntemleri inceleyeceiz.
Standard Template Library
Standard Template Library Standard Template Library
113
C++ ve NESNEYE DAYALI PROGRAMLAMA 225
Standard Template Library (STL) Hewlett Packardn Palo Alto (
California)daki laboratuvarlarnda Alexander Stepanov ve
Meng Lee tarafndan gelitirilmitir.
1970lerin sonlarnda Alexander Stepanov bir ksm
algoritmalarn veri yapsnn nasl depolandklarndan bamsz
olduklarn gzlemledi. rnein, sralama algoritmalarnda
sralanacak saylarn bir dizide mi? yoksa bir listede mi?
bulunduunun bir nemi yoktur. Deien sadece bir sonraki
elemana nasl eriildii ile ilgilidir. Stepanov bu ve benzeri
algoritmalar inceleyerek, algoritmalar veri yapsndan bamsz
olarak performanstan dn vermeksizin soyutlamay
baarmtr. Bu fikrini 1985de Generic ADA dilinde
gerekletirmitir. Ancak o dnemde henz C++da bir nceki
blmde incelediimiz Template yaps bulunmad iin bu
fikrini C++da ancak 1992 ylnda gerekletirebilmitir.
C++ ve NESNEYE DAYALI PROGRAMLAMA 226
Bir yazlm rnnn bileenlerini boyutlu uzayda bir
nokta olarak dnebiliriz :
Generic Programming
Generic Programming Generic Programming
veri tipi : int, float, ...
algoritma :
sralama, kaynatrma, arama ...
container :
dizi, liste, kuyruk ...
j
k
i
(sralama,int,array)
(sralama,double,list)
(sralama,int,list)
...
(sralama,array)
(sralama,list)
...
(sralama)
template template
generic prog. generic prog.
114
C++ ve NESNEYE DAYALI PROGRAMLAMA 227
STL temel bileenden olumaktadr:
Algoritma,
Kap (= Container): nesneleri depolamak ve ynetmekten
sorumlu nesne,
Lineer Kaplar : Vector, Deque, List
Asosyatif Kaplar : Set, Map, Multi-set, Multi-map
Yineleyici (=Iterator): algoritmann farkl tipte kaplarla
almasn salayacak ekilde eriimin soyutlar.
STL Bileenleri
STL Bileenleri STL Bileenleri
C++ ve NESNEYE DAYALI PROGRAMLAMA 228
C++da sabit boyutlu dizi tanmlamak yrtme zamannda bellein ya kt
kullanlmasna yada dizi boyunun yetersiz kalmasna neden olmaktadr.
STL ktphanesindeki vector kab bu sorunlar gidermektedir.
STL ktphanesindeki list kab, balantl liste yapsdr.
deque (Double-Ended QUEue) kab, yn ve kuyruk yaplarnn birleimi olarak
dnlebilir. deque kab her iki utan veri eklemeye ve silmeye olanak salamaktadr.
Vector Vector Relocating,
expandable array Quick random access (by index number).
Slow to insert or erase in the middle.
Quick to insert or erase at end.
List List Doubly linked list Quick to insert or delete at any location.
Quick access to both ends.
Slow random access.
Deque Deque Like vector,
but can be accessed
at either end Quick random access (using index number).
Slow to insert or erase in the middle.
Quick to insert or erase (push and pop) at
either the beginning or the end.
115
C++ ve NESNEYE DAYALI PROGRAMLAMA 229
Empty Empty
Lineer Kaplar : Vector,List, Deque
Lineer Kaplar : Vector,List, Deque Lineer Kaplar : Vector,List, Deque
v = (3,5,5) v = (3,5,5)
v = (3) v = (3)
vector<float> v;
cout << [Link]() << [Link]() ;
[Link]([Link](),3) ;
cout << [Link]() << [Link]() ;
[Link] ([Link](), 2, 5);
v = (9,9,9,9,3,5,5) w=(3, v = (9,9,9,9,3,5,5) w=(3,5,5) 5,5)
w = (9,9,9,9,3,5,5) w = (9,9,9,9,3,5,5)
w = (9,9,9,9) w = (9,9,9,9)
vector<int> w (4,9);
[Link]([Link](), [Link](), [Link]() );
[Link](v) ;
w = (3,5) w = (3,5) [Link]([Link]());
[Link]([Link](),[Link]()) ;
cout << [Link]() ? Empty : not Empty
C++ ve NESNEYE DAYALI PROGRAMLAMA 230
5 5
5 5
v = (3) v = (3)
3 3
v = (3,5) v = (3,5)
vector<float> v;
[Link]([Link](),3) ;
[Link]([Link](),5) ;
cout << [Link]() << endl;
cout << [Link]() ;
v.pop_back();
cout << [Link]() ;
#define __USE_STL
// STL include files
#include vector.h
#include "list.h
116
C++ ve NESNEYE DAYALI PROGRAMLAMA 231
llleeemmm DDDnnn DDDeeeeeerrriii YYYrrrtttllleeennn llleeemmm
UUUyyyggguuulllaaannnaaabbbiiillldddiiiiii
KKKaaappplllaaarrr
[Link]() T& *[Link]() vector, list, deque
[Link]() T& *[Link]() vector, list, deque
a.push_front(x) void [Link]([Link](),x) list,deque
a.push_back(x) void [Link]([Link](),x) vector, list,deque
a.pop_front() void [Link]([Link]()) list,deque
a.pop_back() void [Link](--[Link]()) list,deque
a[n] T& *([Link]()+n) vector,deque
llleeemmm YYYrrrtttllleeennn llleeemmm
[Link]() [Link]() [Link]()
a.max_size()
[Link]() [Link]() == 0
C++ ve NESNEYE DAYALI PROGRAMLAMA 232
Asosyatif Kaplar : Set, Multiset, Map, Multimap
Asosyatif Kaplar : Set, Multiset, Map, Multimap Asosyatif Kaplar : Set, Multiset, Map, Multimap
Set sral kme oluturmak iin kullanlr.
#include <iostream>
#include <set>
#include <string>
using namespace std;
void main(){
string names[] = {"Katie", "Robert","Mary", "Amanda", "Marie"};
set<string> nameSet(names, names+5);// initialize set to array
set<string>::const_iterator iter; // iterator to set
[Link]("Jack"); // insert some more names
[Link]("Larry");
[Link]("Robert"); // no effect; already in set
[Link]("Barry");
[Link]("Mary"); // erase a name
117
C++ ve NESNEYE DAYALI PROGRAMLAMA 233
cout << "\nSize=" << [Link]() << endl;
iter = [Link](); // display members of set
while( iter != [Link]() )
cout << *iter++ << '\n';
string searchName; // get name from user
cout << "\nEnter name to search for: ";
cin >> searchName; // find matching name in set
iter = [Link](searchName);
if( iter == [Link]() )
cout << "The name " << searchName << " is NOT in the set.";
else
cout << "The name " << *iter << " IS in the set.";
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 234
// [Link] set
void main() {
set<string> city;
set<string>::iterator iter;
[Link]("Trabzon"); // insert city names
[Link]("Adana");
[Link]("Edirne");
[Link]("Bursa");
[Link](Istanbul");
[Link]("Rize");
[Link]("Antalya");
[Link]("zmir");
[Link]("Hatay");
[Link]("Ankara");
[Link]("Zonguldak");
118
C++ ve NESNEYE DAYALI PROGRAMLAMA 235
iter = [Link](); // display set
while( iter != [Link]() )
cout << *iter++ << endl;
string lower, upper; // display entries in range
cout << "\nEnter range (example A Azz): ";
cin >> lower >> upper;
iter = city.lower_bound(lower);
while( iter != city.upper_bound(upper) )
cout << *iter++ << endl;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 236
void main(){
map<string,int> city_num;
city_num["Trabzon"]=61;
...
string city_name;
cout << "\nEnter a city: ";
cin >> city_name;
if (city_num.end()== city_num.find(city_name))
cout << city_name << " is not in the database" << endl;
else
cout << "Number of " << city_name << ": " << city_num[city_name];
}
119
C++ ve NESNEYE DAYALI PROGRAMLAMA 237
Iterators
Iterators Iterators
Random Access
Iterators
BIDIRECTIONAL
Iterators
FORWARD
Iterators
INPUT
Iterators
OUTPUT
Iterators
vector, vector, deque deque list list
Iterators : Genelletirilmi areti
OutputIterator r;
InputIterator r;
ForwardIterator r;
BidirectionalIterator r;
RandomIterator r ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 238
Hata
Output Iterators
Output Output Iterators Iterators
OutputIterator a ;
*a=t ;
t = *a ;
Hata
OutputIterator r ;
*r=0 ;
*r=1 ;
Hata
OutputIterator r ;
r++ ;
r++ ;
Hata
OutputIterator i,j ;
i=j ;
*i++=a ;
*j=b ;
120
C++ ve NESNEYE DAYALI PROGRAMLAMA 239
Forward and Bidirectional Iterators
Forward and Bidirectional Forward and Bidirectional Iterators Iterators
John Tom Peter Mary
Andy Bill
range[[Link](),[Link]()] range[[Link](),[Link]()]
list<int> l (1,1) ;
l.push_back(2) ; // list l : 1 2
list<int>::iterator first=[Link]() ;
list<int>::iterator last=[Link]() ;
while( last != first){
-- last ;
cout << *last << ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 240
template<class ForwardIterator, class T>
ForwardIterator find_linear(ForwardIterator first,
ForwardIterator last, T& value){
while( first != last) if( *first++ == value) return first;
else return last ;
}
vector<int> v(3,1) ;
v.push_back(7); // vector : 1 1 1 7
vector<int>::iterator i=find_linear([Link](), [Link](),7) ;
if(i != [Link]() ) cout << *i ;
else cout << not found! ;
121
C++ ve NESNEYE DAYALI PROGRAMLAMA 241
Bubble Sort
Bubble Sort Bubble Sort
template<class Compare>
void bubble_sort(BidirectionalIterator first,
BidirectionalIterator last, Compare comp){
BidirectionalIterator left = first , right = first ;
right ++ ;
while( first != last){
while( right != last ){
if( comp(*right,*left) )
iter_swap(left,right) ;
right++ ;
left++;
}
last -- ;
left = first ; right = first ;
}
}
list<int> l ;
bubble_sort([Link](),[Link](),less<int>()) ;
bubble_sort([Link](),[Link](),greater<int>()) ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 242
Random Access Iterators
Random Access Random Access Iterators Iterators
vector<int> v(1,1) ;
v.push_back(2) ; v.push_back(3) ; v.push_back(4) ; // v : 1 2 3 4
vector<int>::iterator i=[Link]() ;
vector<int>::iterator j=i+2;
cout << *j << ;
i += 3 ; cout << *i << ;
j = i 1 ; cout << *j << ;
j -= 2 ; cout << *j << ;
cout << v[1] << endl ;
(j<i) ? cout << j < i : cout << not j < i ; cout << endl ;
(j>i) ? cout << j > i : cout << not j > i ; cout << endl ;
(j>=i) && (j<=i)? cout << j and i equal : cout << j and i not equal > i ;
cout << endl ;
i = j ;
j= [Link]();
i = [Link] ;
cout << iterator distance end begin : << (i-j) ;
122
C++ ve NESNEYE DAYALI PROGRAMLAMA 243
Generic Algoritma Tasarm
Generic Generic Algoritma Algoritma Tasarm Tasarm
C++ ve NESNEYE DAYALI PROGRAMLAMA 244
const int * binary_search(const int * array, int n, int x){
const int *lo = array, *hi = array + n , *mid ;
while( lo != hi ) {
mid = lo + (hi-lo)/2 ;
if( x == *mid ) return mid ;
if( x < *mid ) hi = mid ;
else lo = mid + 1 ;
}
return 0 ;
}
123
C++ ve NESNEYE DAYALI PROGRAMLAMA 245
template<class T>
const T * binary_search(const T * array, int n, T& x){
const T *lo = array, *hi = array + n , *mid ;
while( lo != hi ) {
mid = lo + (hi-lo)/2 ;
if( x == *mid ) return mid ;
if( x < *mid ) hi = mid ;
else lo = mid + 1 ;
}
return 0 ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 246
template<class T>
const T * binary_search(T * first,T * last, T& x){
const T *lo = first, *hi = last , *mid ;
while( lo != hi ) {
mid = lo + (hi-lo)/2 ;
if( x == *mid ) return mid ;
if( x < *mid ) hi = mid ;
else lo = mid + 1 ;
}
return last ;
}
124
C++ ve NESNEYE DAYALI PROGRAMLAMA 247
template<class RandomAccessIterator,class T>
const T * binary_search(RandomAccessIterator first,
RandomAccessIterator last, T& value){
RandomAccessIterator not_found = last, mid ;
while( lo != hi ) {
mid = first + (last-first)/2 ;
if( x == *mid ) return mid ;
if( x < *mid ) last = mid ;
else first = mid + 1 ;
}
return not_found ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 248
6
Snf Yaps
Kaltm
ok ekillilik
Templates
STL Ktphanesi ve Generic Programming
Stream Ktphanesi
125
C++ ve NESNEYE DAYALI PROGRAMLAMA 249
A stream is a general name given to a flow of data in an input/output situation.
For this reason, streams in C++ are often called iostreams. An iostream can be
represented by an object of a particular class. For example, youve already seen
numerous examples of the cin and cout stream objects used for input and output.
Advantages of Streams
Old-fashioned C programmers may wonder what advantages there are to using
the stream classes for I/O instead of traditional C functions such as printf()
and scanf() andfor filesfprintf(), fscanf(), and so on.
One reason is that the stream classes are less prone to errors. If youve ever
used a %d formatting character when you should have used a %f in printf(),
youll appreciate this. There are no such formatting characters in streams,
because each object already knows how to display itself. This removes a major
source of program bugs.
Second, you can overload existing operators and functions, such as the insertion
(<<) and extraction (>>) operators, to work with classes you create. This makes
your classes work in the same way as the built-in types, which again makes
programming easier and more error free (not to mention more aesthetically
satisfying).
STREAMS
STREAMS
C++ ve NESNEYE DAYALI PROGRAMLAMA 250
The Stream Class Hierarchy
The Stream Class Hierarchy
ios
istream ostream fstreambase
iostream
ifstream
ofstream
fstream
126
C++ ve NESNEYE DAYALI PROGRAMLAMA 251
The ios class is the base class for the iostream hierarchy. It contains many
constants and member functions common to input and output operations of all
kinds. The ios class also contains a pointer to the streambuf class, which
contains the actual memory buffer into which data is read or written and the
low-level routines for handling this data.
The istream and ostream classes are derived from ios and are dedicated to input
and output, respectively. The istream class contains such member functions as
get(), getline(), read(), and the extraction (>>) operators, whereas ostream
contains put() and write() and the insertion (<<) operators.
The iostream class is derived from both istream and ostream by multiple
inheritance. Classes derived from the iostream class can be used with devices,
such as disk files, that may be opened for both input and output at the same
time.
The ifstream class is used for creating input file objects and the ofstream class is
used for creating output file objects. To create a read/write file the fstream
class should be used.
C++ ve NESNEYE DAYALI PROGRAMLAMA 252
The ios class is the grand daddy of all the stream classes and contains the
majority of the features you need to operate C++ streams. The three most
important features are the formatting flags, the error-status bits, and the file
operation mode. Well look at formatting flags and error-status bits now.
Formatting flags are a set of enum definitions in ios. They act as on/off switches
that specify choices for various aspects of input and output format and
operation.
Formatting Flags
skipws Skip (ignore) whitespace on input.
left Left adjust output.
right Right adjust output.
dec Convert to decimal.
oct Convert to octal.
hex Convert to hexadecimal.
showbase Use base indicator on output (0 for octal, 0x for hex).
showpoint Show decimal point on output.
uppercase Use uppercase X, E, and hex output letters ABCDEF.
showpos Display + before positive integers.
scientific Use exponential format on floating-point output [9.1234E2].
fixed Use fixed format on floating-point output [912.34].
unitbuf Flush all streams after insertion.
The ios Class
The ios Class
127
C++ ve NESNEYE DAYALI PROGRAMLAMA 253
There are several ways to set the formatting flags, and different flags can be
set in different ways. Because they are members of the ios class, flags must
usually be preceded by the name ios and the scope-resolution operator (e.g.,
ios::skipws). All the flags can be set using the setf() and unsetf() ios
member functions. For example,
[Link](ios::left); // left justify output text
cout >> "This text is left-justified";
[Link](ios::left); // return to default (right justified)
Many formatting flags can be set using manipulators, so lets look at them
now.
Manipulators
Manipulators are formatting instructions inserted directly into a stream.
Youve seen examples before, such as the manipulator endl, which sends a
new line to the stream and flushes it:
cout << "To each his own." << endl;
There is also used the setiosflags() manipulator:
cout << setiosflags(ios::fixed) // use fixed decimal point
<< setiosflags(ios::showpoint) //always show decimal point
<< var;
C++ ve NESNEYE DAYALI PROGRAMLAMA 254
ws Turn on whitespace skipping on input.
dec Convert to decimal.
oct Convert to octal.
hex Convert to hexadecimal.
endl Insert new line and flush the output stream.
ends Insert null character to terminate an output string.
flush Flush the output stream.
lock Lock file handle.
unlock Unlock file handle.
You insert these manipulators directly into the stream. For example, to
output var in hexadecimal format, you can say
cout << hex << var;
No-argument ios Manipulators
No-argument ios Manipulators
128
C++ ve NESNEYE DAYALI PROGRAMLAMA 255
setw() field width (int) Set field width for output.
setfill() fill character (int) Set fill character for output (default is a space).
setprecision() precision (int) Set precision (number of digits displayed). setiosflags()
formatting flags (long) Set specified flags.
resetiosflags() formatting flags (long) Clear specified flags.
Manipulators that take arguments affect only the next item in the stream. For
example, if you use setw to set the width of the field in which one number is
displayed, youll need to use it again for the next number.
ios manipulators with arguments
Functions
The ios class contains a number of functions that you can use to set the formatting
flags and perform other tasks. most of these functions are shown below:
ch = fill(); Return the fill character (fills unused part of field; default is space).
fill(ch); Set the fill character.
p = precision() Get the precision (number of digits displayed for floating point).
precision(p); Set the precision.
w = width(); Get the current field width (in characters).
width(w); Set the current field width.
setf(flags); Set specified formatting flags (e.g., ios::left).
unsetf(flags); Unset specified formatting flags.
C++ ve NESNEYE DAYALI PROGRAMLAMA 256
These functions are called for specific stream objects using the normal dot
operator. For example, to set the field width to 14, you can say
[Link](14);
Similarly, the following statement sets the fill character to an asterisk (as for
check printing):
[Link]('*');
You can use several functions to manipulate the ios formatting flags directly. For
example, to set left justification, use
[Link](ios::left);
To restore right justification, use
[Link](ios::left);
The istream Class
The istream class, which is derived from ios, performs input-specific activities.
istream functions:
>> Formatted extraction for all basic (and overloaded) types.
get(ch); Extract one character into ch.
get(str) Extract characters into array str, until \0.
get(str, MAX) Extract up to MAX characters into array.
get(str, DELIM) Extract characters into array str until specified delimiter
(typically \n).
Leave delimiting char in stream.
129
C++ ve NESNEYE DAYALI PROGRAMLAMA 257
get(str, MAX, DELIM) Extract characters into array str until MAX characters or the
DELIM character. Leave delimiting char in stream.
getline(str, MAX, DELIM) Extract characters into array str until MAX characters or the
DELIM character. Extract delimiting character.
putback(ch) Insert last character read back into input stream.
ignore(MAX, DELIM) Extract and discard up to MAX characters until (and including)
the specified delimiter (typically \n).
peek(ch) Read one character, leave it in stream.
count = gcount() Return number of characters read by a (immediately preceding)
call to get(), getline(), or read().
read(str, MAX) For files. Extract up to MAX characters into str until EOF.
seekg(position) Sets distance (in bytes) of file pointer from start of file.
seekg(position, seek_dir) Sets distance (in bytes) of file pointer from specified place in
file: seek_dir can be ios::beg, ios::cur, ios::end.
position = tellg(pos) Return position (in bytes) of file pointer from start of file.
istream functions:
C++ ve NESNEYE DAYALI PROGRAMLAMA 258
The ostream Class
The ostream class handles output or insertion activities.
ostreamfunctions:
<< Formatted insertion for all basic (and overloaded) types.
put(ch) Insert character ch into stream.
flush() Flush buffer contents and insert new line.
write(str, SIZE) Insert SIZE characters from array str into file.
seekp(position) Sets distance in bytes of file pointer from start of file.
seekp(position, seek_dir) Set distance in bytes of file pointer from specified place in
file. seek_dir can be ios::beg, ios::cur, or ios::end.
position = tellp() Return position of file pointer, in bytes.
The iostreamand the _withassign Classes
The iostream class, which is derived from both istream and ostream, acts only as a base class
from which other classes, specifically iostream_withassign, can be derived. It has no
functions of its own (except constructors and destructors). Classes derived from iostream can
perform both input and output.
There are three _withassign classes:
istream_withassign, derived from istream
ostream_withassign, derived from ostream
iostream_withassign, derived from iostream
These _withassign classes are much like those theyre derived from except they include
overloaded assignment operators so their objects can be copied.
130
C++ ve NESNEYE DAYALI PROGRAMLAMA 259
Objects Name Class Used for
cin istream_withassign Keyboard input
cout ostream_withassign Normal screen output
cerr ostream_withassign Error output
clog ostream_withassign Log output
The cerr object is often used for error messages and program diagnostics.
Output sent to cerr is displayed immediately, rather than being buffered,
as output sent to cout is. Also, output to cerr cannot be redirected. For
these reasons, you have a better chance of seeing a final output message
from cerr if your program dies prematurely. Another object, clog, is similar
to cerr in that it is not redirected, but its output is buffered, whereas
cerrs is not.
Predefined Stream Objects
Stream Errors
What happens if a user enters the string nine instead of the integer 9, or
pushes ENTER without entering anything? What happens if theres a
hardware failure? Well explore such problems in this session. Many of the
techniques youll see here are applicable to file I/O as well.
C++ ve NESNEYE DAYALI PROGRAMLAMA 260
The stream error-status bits (error byte) are an ios member that report
errors that occurred in an input or output operation.
goodbit No errors (no bits set, value = 0).
eofbit Reached end of file.
failbit Operation failed (user error, premature EOF).
badbit Invalid operation (no associated streambuf).
hardfail Unrecoverable error.
Various ios functions can be used to read (and even set) these error bits.
int = eof(); Returns true if EOF bit set.
int = fail(); Returns true if fail bit or bad bit or hard-fail bit set.
int = bad(); Returns true if bad bit or hard-fail bit set.
int = good(); Returns true if everything OK; no bits set.
clear(int=0); With no argument, clears all error bits;
otherwise sets specified bits, as in clear(ios::failbit).
Error-Status Bits
Error-Status Bits
131
C++ ve NESNEYE DAYALI PROGRAMLAMA 261
#include <iostream.h>
void main()
{
int i;
char ok=0;
while(!ok) // cycle until input OK
{
cout << "\nEnter an integer: ";
cin >> i;
if( [Link]() ) // if no errors
ok=1;
else
{
[Link](); // clear the error bits
cout << "Incorrect input";
[Link](20, '\n'); // remove newline
}
}
cout << "integer is " << i; // error-free integer
}
See Example: [Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 262
Whitespace characters, such as TAB, ENTER , and \n, are normally ignored (skipped)
when inputting numbers. This can have some undesirable side effects. For example,
users, prompted to enter a number, may simply press the key without typing any digits.
Pressing ENTER causes the cursor to drop down to the next line while the stream
continues to wait for the number. Whats wrong with the cursor dropping to the next
line? First, inexperienced users, seeing no acknowledgment when they press , may
assume the computer is broken. Second, pressing repeatedly normally causes the
cursor to drop lower and lower until the entire screen begins to scroll upward. Thus
its important to be able to tell the input stream not to ignore whitespace. This is done
by clearing the skipws flag:
cout << "\nEnter an integer: ";
[Link](ios::skipws); // don't ignore whitespace
cin >> i;
if( [Link]() )
{
// no error
}
// error
Now if the user types without any digits, failbit will be set and an error will be
generated. The program can then tell the user what to do or reposition the cursor so
the screen does not scroll.
No-Input Input
No-Input Input
132
C++ ve NESNEYE DAYALI PROGRAMLAMA 263
Disk File I/O with Streams
Disk files require a different set of classes than files used with the keyboard and
screen. These are ifstream for input, fstream for input and output, and ofstream for
output. Objects of these classes can be associated with disk files and you can use
their member functions to read and write to the files.
The ifstream, ofstream, and fstream classes are declared in the FSTREAM.H file.
This file also includes the IOSTREAM.H header file, so there is no need to include it
explicitly; FSTREAM.H takes care of all stream I/O.
#include <fstream.h> // for file I/O
void main()
{
char ch = 'x'; // character
int j = 77; // integer
double d = 6.02; // floating point
char str1[] = "Kafka"; // strings
char str2[] = "Proust"; // (no embedded spaces)
ofstream outfile("[Link]"); // create ofstream object
outfile << ch // insert (write) data
<< j << ' ' // needs space between numbers
<< d
<< str1 << ' ' // needs space between strings
<< str2;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 264
Here the program defines an object called outfile to be a member of the
ofstream class. At the same time, it initializes the object to the file name
[Link]. This initialization sets aside various resources for the file, and
accesses or opens the file of that name on the disk. If the file doesnt exist, it
is created. If it does exist, it is truncated and the new data replaces the old.
The outfile object acts much as cout did in previous programs, so the insertion
operator (<<) is used to output variables of any basic type to the file. This
works because the insertion operator is appropriately overloaded in ostream,
from which ofstream is derived.
When the program terminates, the outfile object goes out of scope. This calls
its destructor, which closes the file, so you dont need to close the file
explicitly.
You must separate numbers (such as 77 and 6.02) with nonnumeric characters.
Because numbers are stored as a sequence of characters rather than as a
fixed-length field, this is the only way the extraction operator will know, when
the data is read back from the file, where one number stops and the next one
begins. Second, strings must be separated with whitespace for the same
reason. This implies that strings cannot contain embedded blanks. In this
example, I use the space character ( ) for both kinds of delimiters.
Characters need no delimiters, because they have a fixed length.
133
C++ ve NESNEYE DAYALI PROGRAMLAMA 265
Any program can read the file generated by previous program by using an ifstream
object that is initialized to the name of the file. The file is automatically opened
when the object is created. The program can then read from it using the extraction
(>>) operator.
// reads formatted output from a file, using >>
#include <fstream.h>
const int MAX = 80;
void main()
{
char ch; // empty variables
int j;
double d;
char str1[MAX];
char str2[MAX];
ifstream infile("[Link]"); // create ifstream object
infile >> ch >> j >> d >> str1 >> str2; // extract (read) data from it
cout << ch << endl // display the data
<< j << endl
<< d << endl
<< str1 << endl
<< str2 << endl;
}
Reading Data
Reading Data
C++ ve NESNEYE DAYALI PROGRAMLAMA 266
Objects derived from ios contain error-status bits that can be checked to
determine the results of operations. When you read a file little by little, you
will eventually encounter an end-of-file condition. The EOF is a signal sent to
the program from the hardware when there is no more data to read. The
following construction can be used to check for this:
while( ![Link]() ) // until eof encountered
However, checking specifically for an eofbit means that I wont detect the
other error bits, such as the failbit and badbit, which may also occur, although
more rarely. To do this, I could change the loop condition:
while( [Link]() ) // until any error encountered
But even more simply, I can test the stream directly
while( infile ) // until any error encountered
Any stream object, such as infile, has a value that can be tested for the usual
error conditions, including EOF. If any such condition is true, the object
returns a zero value. If everything is going well, the object returns a nonzero
value. This value is actually a pointer, but the address returned has no
significance except to be tested for a zero or nonzero value.
Detecting End-of-File
Detecting End-of-File
134
C++ ve NESNEYE DAYALI PROGRAMLAMA 267
You can write a few numbers to disk using formatted I/O, but if youre
storing a large amount of numerical data, its more efficient to use binary
I/O in which numbers are stored as they are in the computers RAM
memory rather than as strings of characters. In binary I/O an integer is
always stored in 2 bytes, whereas its text version might be 12345,
requiring 5 bytes. Similarly, a float is always stored in 4 bytes, whereas its
formatted version might be 6.02314e13, requiring 10 bytes.
The next example shows how an array of integers is written to disk and
then read back into memory using binary format. I use two new functions:
write(), a member of ofstream, and read(), a member of ifstream. These
functions think about data in terms of bytes (type char). They dont care
how the data is formatted, they simply transfer a buffer full of bytes
from and to a disk file. The parameters to write() and read() are the
address of the data buffer and its length. The address must be cast to
type char, and the length is the length in bytes (characters), not the
number of data items in the buffer.
Binary I/O
Binary I/O
C++ ve NESNEYE DAYALI PROGRAMLAMA 268
// binary input and output with integers
#include <fstream.h> // for file streams
const int MAX = 100; // number of ints
int buff[MAX]; // buffer for integers
void main()
{
int j;
for(j=0; j<MAX; j++) // fill buffer with data
buff[j] = j; // (0, 1, 2, ...)
ofstream os("[Link]", ios::binary); // create output stream
[Link]( (char*)buff, MAX*sizeof(int) ); // write to it
[Link](); // must close it
for(j=0; j<MAX; j++) // erase buffer
buff[j] = 0;
ifstream is("[Link]", ios::binary); // create input stream
[Link]( (char*)buff, MAX*sizeof(int) ); // read from it
for(j=0; j<MAX; j++) // check data
if( buff[j] != j ) cerr << "\nData is incorrect";
else cout << "\nData is correct";
}
Example
135
C++ ve NESNEYE DAYALI PROGRAMLAMA 269
When writing an object, you generally want to use binary mode. This writes
the same bit configuration to disk that was stored in memory and ensures
that numerical data contained in objects is handled properly.
// saves person object to disk
#include <fstream.h> // for file streams
class person // class of persons
{
protected:
char name[40]; // person's name
int age; // person's age
public:
void getData(void) // get person's data
{
cout << "Enter name: "; cin >> name;
cout << "Enter age: "; cin >> age;
}
};
Writing an Object to Disk
Writing an Object to Disk
C++ ve NESNEYE DAYALI PROGRAMLAMA 270
void main(void)
{
person pers; // create a person
[Link](); // get data for person
ofstream outfile("[Link]", ios::binary); // create ofstream object
[Link]( (char*)&pers, sizeof(pers) ); // write to it
}
// reads person object from disk
#include <fstream.h> // for file streams
class person // class of persons
{
protected:
char name[40]; // person's name
int age; // person's age
public:
void showData(void) // display person's data
{
cout << "\n Name: " << name;
cout << "\n Age: " << age;
}
};
Reading an Object from Disk
136
C++ ve NESNEYE DAYALI PROGRAMLAMA 271
void main(void)
{
person pers; // create person variable
ifstream infile("[Link]", ios::binary); // create stream
[Link]( (char*)&pers, sizeof(pers) ); // read stream
[Link](); // display person
}
To work correctly, programs that read and write objects to files, must be
working on the same class of objects. Objects of class person in these
programs are exactly 42 bytes long, with the first 40 occupied by a string
representing the persons name and the last 2 containing an int representing
the persons age.
Notice, however, that although the person classes in both programs have the
same data, they may have different member functions. The first includes
the single function getData(), whereas the second has only showData(). It
doesnt matter what member functions you use, because members functions
are not written to disk along with the objects data. The data must have the
same format, but inconsistencies in the member functions have no effect.
This is true only in simple classes that dont use virtual functions.
C++ ve NESNEYE DAYALI PROGRAMLAMA 272
// reads and writes several objects to disk
#include <fstream.h> // for file streams
class person // class of persons
{
protected:
char name[40]; // person's name
int age; // person's age
public:
void getData() // get person's data
{
cout << "\n Enter name: "; cin >> name;
cout << " Enter age: "; cin >> age;
}
void showData() // display person's data
{
cout << "\n Name: " << name;
cout << "\n Age: " << age;
}
};
I/O with Multiple Objects
I/O with Multiple Objects
137
C++ ve NESNEYE DAYALI PROGRAMLAMA 273
void main()
{
char ch;
person pers; // create person object
fstream file; // create input/output file
[Link]("[Link]", ios::app | ios::out | ios::in | ios::binary ); // open for append
do{ // data from user to file
cout << "\nEnter person's data:";
[Link](); // get one person's data
[Link]( (char*)&pers, sizeof(pers) ); // write to file
cout << "Enter another person (y/n)? ";
cin >> ch;
} while(ch=='y'); // quit on 'n'
[Link](0); // reset to start of file
[Link]( (char*)&pers, sizeof(pers) ); // read first person
while( ![Link]() ) // quit on EOF
{
cout << "\nPerson:"; // display person
[Link]();
[Link]( (char*)&pers, sizeof(pers) ); // read another
} // person
} See Example: [Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 274
Reacting to Errors
The next program shows how errors are most conveniently handled. All disk operations
are checked after they are performed. If an error has occurred, a message is printed
and the program terminates. We will use the technique, discussed earlier, of checking
the return value from the object itself to determine its error status. The program
opens an output stream object, writes an entire array of integers to it with a single
call to write(), and closes the object. Then it opens an input stream object and reads
the array of integers with a call to read().
// handles errors during input and output
#include <fstream.h> // for file streams
#include <process.h> // for exit()
const int MAX = 1000;
int buff[MAX];
void main()
{
int j;
for(j=0; j<MAX; j++) buff[ j ] = j; // fill buffer with data
ofstream os; // create output stream
[Link]("[Link]", ios::trunc | ios::binary); // open it
if(!os) { cerr << "\nCould not open output file"; exit(1); }
cout << "\nWriting..."; // write buffer to it
[Link]( (char*)buff, MAX*sizeof(int) );
if(!os) { cerr << "\nCould not write to file"; exit(1); }
[Link](); // must close it
138
C++ ve NESNEYE DAYALI PROGRAMLAMA 275
for(j=0; j<MAX; j++) buff[ j ] = 0; // clear buffer
ifstream is; // create input stream
[Link]("[Link]", ios::binary);
if(!is) { cerr << "\nCould not open input file"; exit(1); }
cout << "\nReading...";
[Link]( (char*)buff, MAX*sizeof(int) ); // read file
if(!is) { cerr << "\nCould not read from file"; exit(1); }
for(j=0; j<MAX; j++) // check data
if( buff[j] != j ) { cerr << "\nData is incorrect"; exit(1); }
cout << "\nData is correct";
}
Analyzing Errors
In the previous example, we determined whether an error occurred in an
I/O operation by examining the return value of the entire stream object.
if(!is)
// error occurred
However, its also possible, using the ios error-status bits, to find out more
specific information about a file I/O error.
C++ ve NESNEYE DAYALI PROGRAMLAMA 276
// checks for errors opening file
#include <fstream.h> // for file functions
void main()
{
ifstream file;
[Link]("[Link]", ios::nocreate);
if( !file )
cout << endl <<"Can't open [Link]";
else
cout << endl << "File opened successfully.";
cout << endl << "file = " << file;
cout << endl << "Error state = " << [Link]();
cout << endl << "good() = " << [Link]();
cout << endl << "eof() = " << [Link]();
cout << endl << "fail() = " << [Link]();
cout << endl << "bad() = " << [Link]();
[Link]();
}
139
C++ ve NESNEYE DAYALI PROGRAMLAMA 277
This program first checks the value of the object file. If its value is
zero, the file probably could not be opened because it didnt exist.
Heres the output of the program when thats the case:
Can't open [Link]
file = 0x1c730000
Error state = 4
good() = 0
eof() = 0
fail() = 4
bad() = 4
The error state returned by rdstate() is 4. This is the bit that
indicates the file doesnt exist; its set to 1. The other bits are all
set to 0. The good() function returns 1 (true) only when no bits are
set, so it returns 0 (false). Im not at EOF, so eof() returns 0. The
fail() and bad() functions return nonzero because an error occurred.
In a serious program, some or all of these functions should be used
after every I/O operation to ensure that things have gone as
expected.
C++ ve NESNEYE DAYALI PROGRAMLAMA 278
// seeks particular person in file
#include <fstream.h> // for file streams
class person // class of persons
{
protected:
char name[40]; // person's name
int age; // person's age
public:
void showData() // display person's data
{
cout << "\n Name: " << name; cout << "\n Age: " << age;
}
};
Each file object has associated with it two integer values called the get pointer and
the put pointer. These are also called the current get position and the current put
position, orif its clear which one is meantsimply the current position. These
values specify the byte number in the file where writing or reading will take place
There are times when you must take control of the file pointers yourself so that you
can read from or write to an arbitrary location in the file. The seekg() and tellg()
functions allow you to set and examine the get pointer, and the seekp() and tellp()
functions perform the same actions on the put pointer.
File Pointers
File Pointers
140
C++ ve NESNEYE DAYALI PROGRAMLAMA 279
void main()
{
person pers; // create person object
ifstream infile; // create input file
[Link]("[Link]", ios::binary); // open file
[Link](0, ios::end); // go to 0 bytes from end
int endposition = [Link](); // find where we are
int n = endposition / sizeof(person); // number of persons
cout << endl << "There are " << n << " persons in file";
cout << endl << "Enter person number: "; cin >> n;
int position = (n-1) * sizeof(person); // number times size
[Link](position); // bytes from begin
[Link]( (char*)&pers, sizeof(pers) ); // read one person
[Link](); // display the person
}
Heres the output from the program, assuming that the [Link] file
contains 3 persons:
There are 3 persons in file
Enter person number: 2
Name: Rainier
Age: 21
C++ ve NESNEYE DAYALI PROGRAMLAMA 280
So far, weve let the main() function handle the details of file
I/O. This is nice for demonstrations, but in real object-oriented
programs, its natural to include file I/O operations as member
functions of the class.
In the next example, we will add member functions, diskOut() and
diskIn() to the person class. These functions allow a person object
to write itself to disk and read itself back in.
Simplifying assumptions: First, all objects of the class will be
stored in the same file, called [Link]. Second, new objects
are always appended to the end of the file. An argument to the
diskIn() function allows me to read the data for any person in the
file. To prevent attempts to read data beyond the end of the file,
I include a static member function, diskCount(), that returns the
number of persons stored in the file.
File I/O Using Member Functions
File I/O Using Member Functions
141
C++ ve NESNEYE DAYALI PROGRAMLAMA 281
// person objects do disk I/O
#include <fstream.h> // for file streams
class person // class of persons
{
protected:
char name[40]; // person's name
int age; // person's age
public:
void getData() // get person's data
{ cout << "\n Enter name: "; cin >> name; cout << " Enter age: "; cin >> age; }
void showData() // display person's data
{ cout << "\n Name: " << name; cout << "\n Age: " << age; }
void diskIn(int ); // read from file
void diskOut(); // write to file
static int diskCount(); // return number of persons in file
};
void person::diskIn(int pn) // read person number pn from file
{
ifstream infile; // make stream
[Link]("[Link]", ios::binary); // open it
[Link]( pn*sizeof(person) ); // move file ptr
[Link]( (char*)this, sizeof(*this) ); // read one person
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 282
void person::diskOut() // write person to end of file
{
ofstream outfile; // make stream
[Link]("[Link]", ios::app | ios::binary); // open it
[Link]( (char*)this, sizeof(*this) ); // write to it
}
int person::diskCount() // return number of persons in file
{
ifstream infile;
[Link]("[Link]", ios::binary);
[Link](0, ios::end); // go to 0 bytes from end
return [Link]() / sizeof(person); // calculate number of persons
}
142
C++ ve NESNEYE DAYALI PROGRAMLAMA 283
void main(void)
{
person p; // make an empty person
char ch;
do // save persons to disk
{
cout << "\nEnter data for person:";
[Link](); // get data
[Link](); // write to disk
cout << "Do another (y/n)? ";
cin >> ch;
}
while(ch=='y'); // until user enters 'n'
int n = person::diskCount(); // how many persons in file?
cout << "\nThere are " << n << " persons in file";
for(int j=0; j<n; j++) // for each one,
{
cout << "\nPerson #" << (j+1);
[Link](j); // read person from disk
[Link](); // display person
}
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 284
In this session Ill show how to overload the extraction and insertion operators. This is
a powerful feature of C++. It lets you treat I/O for user-defined data types in the
same way as for basic types such as int and double. For example, if you have an object
of class ComplexT called c1, you can display it with the statement
cout << c1;
just as if it were a basic data type.
You can overload the extraction and insertion operators so they work with the display
and keyboard (cout and cin). With a little more care, you can also overload them so
they work with disk files as well.
#include<iostream.h>
class ComplexT{
float re,im;
friend istream& operator >>(istream&, ComplexT&);
friend ostream& operator <<(ostream&, const ComplexT&);
public:
ComplexT(float re_in=0,float im_in=0){re=re_in;im=im_in;}
ComplexT operator+(const ComplexT&);
};
Overloading the << and >> Operators
Overloading the << and >> Operators
143
C++ ve NESNEYE DAYALI PROGRAMLAMA 285
istream& operator >>(istream& stream, ComplexT& z) // Overloading >>
{
cout << "Enter real part:";
stream >> [Link];
cout << "Enter imaginer part:";
stream >> [Link];
return stream;
};
ostream& operator <<(ostream& stream, const ComplexT& z) // Overloading <<
{
stream << "( " << [Link] << " , " << [Link] << " ) \n";
return stream;
};
ComplexT ComplexT::operator+(const ComplexT& z) // Operator +
{
return ComplexT(re+[Link] , im+[Link]);
}
void main()
{
ComplexT z1,z2,z3;
cin>>z1;
cin>>z2;
z3=z1+z2;
cout << " Result=" << z3;
}
See Example: [Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 286
Overloading for Files
The next example shows how the << and >> operators can be overloaded so
they work with both file I/O and cout and cin.
#include<fstream.h>
class ComplexT{
float re,im;
friend istream& operator >>(istream&, ComplexT&);
friend ostream& operator <<(ostream&, const ComplexT&);
public:
ComplexT(float re_in=0,float im_in=0){re=re_in;im=im_in;}
};
istream& operator >>(istream& stream, ComplexT& z)
{
char dummy;
stream >> dummy >> [Link];
stream >> dummy >> [Link] >> dummy;
return stream;
};
ostream& operator <<(ostream& stream, const ComplexT& z){
stream << "(" << [Link] << " , " << [Link] << ") \n";
return stream;
};
144
C++ ve NESNEYE DAYALI PROGRAMLAMA 287
void main()
{
char ch;
ComplexT z1;
ofstream ofile; // create and open
[Link]("[Link]"); // output stream
do{
cout << "\nEnter Complex Number:(re,im)";
cin >> z1; // get complex number from user
ofile << z1; // write it to output str
cout << "Do another (y/n)? ";
cin >> ch;
}while(ch != 'n');
[Link](); // close output stream
ifstream ifile; // create and open
[Link]("[Link]"); // input stream
cout << "\nContents of disk file is:";
while(![Link]())
{
ifile >> z1; // read complex number from stream
if(ifile)
cout << "\nComplex Number = " << z1; // display complex number
}
}
See Example: [Link]
C++ ve NESNEYE DAYALI PROGRAMLAMA 288
So far, youve seen examples of overloading operator<<() and operator>>() for
formatted I/O. They also can be overloaded to perform binary I/O. This may be a
more efficient way to store information, especially if your object contains much
numerical data.
#include <fstream.h> // for file streams
class person // class of persons
{
protected:
char name[40]; // person's name
int age; // person's age
public:
void getData() // get data from keyboard
{
cout << "\n Enter name: "; [Link](name, 40);
cout << " Enter age: "; cin >> age;
}
void putData() // display data on screen
{
cout << "\n Name = " << name; cout << "\n Age = " << age;
}
friend istream& operator >> (istream& s, person& d);
friend ostream& operator << (ostream& s, person& d);
Overloading for Binary I/O
Overloading for Binary I/O
145
C++ ve NESNEYE DAYALI PROGRAMLAMA 289
void persin(istream& s) // read file into ourself
{
[Link]( (char*)this, sizeof(*this) );
}
void persout(ostream& s) // write our data to file
{
[Link]( (char*)this, sizeof(*this) );
}
}; // end of class definiton
istream& operator >> (istream& s, person& d) // get data from disk
{
[Link](s);
return s;
}
ostream& operator << (ostream& s, person& d) // write data to disk
{
[Link](s);
return s;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 290
void main()
{ // create 4 persons
person pers1, pers2, pers3, pers4;
cout << "\nPerson 1";
[Link](); // get data for pers1
cout << "\nPerson 2";
[Link](); // get data for pers2
outfile("[Link]", ios::binary); // create output stream
ofstream
outfile << pers1 << pers2; // write to file
[Link]();
ifstream infile("[Link]", ios::binary); // create input stream
infile >> pers3 >> pers4; // read from file into
cout << "\nPerson 3"; // pers3 and pers4
[Link](); // display new objects
cout << "\nPerson 4";
[Link]();
}
146
Exceptions Exceptions
C++ ve NESNEYE DAYALI PROGRAMLAMA 292
Kinds of errors with programs
Poor logic - bad algorithm
Improper syntax - bad implementation
Exceptions - Unusual, but predictable problems
The earlier you find an error, the less it
costs to fix it
Modern compilers find errors early
Program Errors
Program Errors
147
C++ ve NESNEYE DAYALI PROGRAMLAMA 293
In C, the default response to an error is to continue,
possibly generating a message
In C++, the default response to an error is to
terminate the program
C++ programs are more brittle, and you have to
strive to get them to work correctly
Can catch all errors and continue as C does
Paradigm Shift from C
Paradigm Shift from C
C++ ve NESNEYE DAYALI PROGRAMLAMA 294
a macro (processed by the precompiler)
Returns TRUE if its parameter is TRUE
Takes an action if it is FALSE
abort the program
throw an exception
If DEBUG is not defined, asserts are collapsed so
that they generate no code
assert()
assert()
148
C++ ve NESNEYE DAYALI PROGRAMLAMA 295
When writing your program, if you know something is true,
you can use an assert
If you have a function which is passed a pointer, you can do
assert(pTruck);
if pTruck is 0, the assertion will fail
Use of assert can provide the code reader with insight to your
train of thought
assert() (contd)
assert() (contd)
C++ ve NESNEYE DAYALI PROGRAMLAMA 296
Assert is only used to find programming errors
Runtime errors are handled with exceptions
DEBUG false => no code generated for assert
Animal *pCat = new Cat;
assert(pCat); // bad use of assert
pCat->memberFunction();
assert() (contd)
assert() (contd)
149
C++ ve NESNEYE DAYALI PROGRAMLAMA 297
assert() can be helpful
Dont overuse it
Dont forget that it instruments your code
invalidates unit test when you turn DEBUG off
Use the debugger to find errors
assert() (contd)
assert() (contd)
C++ ve NESNEYE DAYALI PROGRAMLAMA 298
You can fix poor logic (code reviews, debugger)
You can fix improper syntax (asserts, debugger)
You have to live with exceptions
Run out of resources (memory, disk space)
User enters bad data
Floppy disk goes bad
Exceptions
Exceptions
150
C++ ve NESNEYE DAYALI PROGRAMLAMA 299
The types of problems which cause exceptions
(running out of resources, bad disk drive) are found
at a low level (say in a device driver)
The low level code implementer does not know
what your application wants to do when the
problem occurs, so s/he throws the problem up
to you
Why are Exceptions Needed?
Why are Exceptions Needed?
C++ ve NESNEYE DAYALI PROGRAMLAMA 300
Crash the program
Display a message and exit
Display a message and allow the user to continue
Correct the problem and continue without
disturbing the user
Murphy's Law: "Never test for a system
error you don't know how to handle."
How To Deal With Exceptions
How To Deal With Exceptions
151
C++ ve NESNEYE DAYALI PROGRAMLAMA 301
An object
passed from the area where the problem occurs
passed to the area where the problem is
handled
The type of object determines which exception
handler will be used
What is a C++ Exception?
What is a C++ Exception?
C++ ve NESNEYE DAYALI PROGRAMLAMA 302
try { try {
// a block of code which might generate an exception // a block of code which might generate an exception
} }
catch(xNoDisk catch(xNoDisk) { ) {
// the exception // the exception handler(tell handler(tell the user to the user to
// // insert a insert a disk) disk)
} }
catch(xNoMemory catch(xNoMemory) { ) {
// another exception handler for this try block // another exception handler for this try block
} }
Syntax
Syntax
152
C++ ve NESNEYE DAYALI PROGRAMLAMA 303
Defined like any other class:
class Set {
private:
int *pData;
public:
...
class xBadIndex {}; // just like any other class
};
The Exception Class
The Exception Class
C++ ve NESNEYE DAYALI PROGRAMLAMA 304
In your code where you reach an error node:
if(memberIndex < 0)
throw xBadIndex();
Exception processing now looks for a catch block
which can handle your thrown object
If there is no corresponding catch block in the
immediate context, the call stack is examined
Throwing An Exception
Throwing An Exception
153
C++ ve NESNEYE DAYALI PROGRAMLAMA 305
As your program executes, and functions are
called, the return address for each function is
stored on a push down stack
At runtime, the program uses the stack to return to
the calling function
Exception handling uses it to find a catch block
The Call Stack
The Call Stack
C++ ve NESNEYE DAYALI PROGRAMLAMA 306
The exception is passed up the call stack until an appropriate
catch block is found
As the exception is passed up, the destructors for objects on the
data stack are called
There is no going back once the exception is raised
Passing The Exception
Passing The Exception
154
C++ ve NESNEYE DAYALI PROGRAMLAMA 307
Once an appropriate catch block is found, the code in the catch
block is executed
Control is then given to the statement after the group of catch
blocks
Only the active handler most recently encountered in the thread
of control will be invoked
Handling The Exception
Handling The Exception
C++ ve NESNEYE DAYALI PROGRAMLAMA 308
catch (Set::xBadIndex) {
// display an error message
}
catch (Set::xBadData) {
// handle this other exception
}
//control is given back here
If no appropriate catch block is found, and the stack is at main(),
the program exits
Handling The Exception (contd)
Handling The Exception (contd)
155
C++ ve NESNEYE DAYALI PROGRAMLAMA 309
Similar to the switch statement
catch (Set::xBadIndex)
{ // display an error message }
catch (Set::xBadData)
{ // handle this other exception }
catch ()
{ // handle any other exception }
Default catch Specifications
Default catch Specifications
C++ ve NESNEYE DAYALI PROGRAMLAMA 310
Exception classes are
just like every other
class; you can derive
classes from them
So one try/catch block
might catch all bad
indices, and another
might catch only
negative bad indices
xBadIndex
xNegative xTooLarge
Exception Hierarchies
Exception Hierarchies
156
C++ ve NESNEYE DAYALI PROGRAMLAMA 311
class Set {
private:
int *pData;
public:
class xBadIndex {};
class xNegative : public xBadIndex {};
class xTooLarge: public xBadIndex {};
};
// throwing xNegative will be
// caught by xBadIndex, too
Exception Hierarchies (contd)
Exception Hierarchies (contd)
C++ ve NESNEYE DAYALI PROGRAMLAMA 312
Since Exceptions are just like other classes, they
can have data and member functions
You can pass data along with the exception object
An example is to pass an error subtype
for xBadIndex, you could throw the type of bad
index
Data in Exceptions
Data in Exceptions
157
C++ ve NESNEYE DAYALI PROGRAMLAMA 313
// Add member // Add member data,ctor,dtor,accessor data,ctor,dtor,accessor method method
class class xBadIndex xBadIndex { {
private: private:
int int badIndex badIndex; ;
public: public:
xBadIndex(int xBadIndex(int iType):badIndex(iType iType):badIndex(iType) {} ) {}
int int GetBadIndex GetBadIndex () { return () { return badIndex badIndex; } ; }
~ ~xBadIndex xBadIndex() {} () {}
}; };
Data in Exceptions (Continued)
Data in Exceptions (Continued)
C++ ve NESNEYE DAYALI PROGRAMLAMA 314
// the place in the code where the index is used // the place in the code where the index is used
if (index < 0) if (index < 0)
throw throw xBadIndex(index xBadIndex(index); );
if (index > MAX) if (index > MAX)
throw throw xBadIndex(index xBadIndex(index); );
// index is ok // index is ok
Passing Data In Exceptions
Passing Data In Exceptions
158
C++ ve NESNEYE DAYALI PROGRAMLAMA 315
catch ( catch (Set::xBadIndex Set::xBadIndex theException theException) )
{ {
int int badIndex badIndex = = [Link] [Link](); ();
if ( if (badIndex badIndex < 0 ) < 0 )
cout << Set Index << cout << Set Index << badIndex badIndex << less than 0; << less than 0;
else else
cout << Set Index << cout << Set Index << badIndex badIndex << too large; << too large;
cout << cout << endl endl; ;
} }
Getting Data From Exceptions
Getting Data From Exceptions
C++ ve NESNEYE DAYALI PROGRAMLAMA 316
When you write an exception handler, stay aware
of the problem that caused it
Example: if the exception handler is for an out of
memory condition, you shouldnt have statements
in your exception object constructor which allocate
memory
Caution
Caution
159
C++ ve NESNEYE DAYALI PROGRAMLAMA 317
You can create a single exception for all instances of
a template
declare the exception outside of the template
You can create an exception for each instance of the
template
declare the exception inside the template
Exceptions With Templates
Exceptions With Templates
C++ ve NESNEYE DAYALI PROGRAMLAMA 318
class class xSingleException xSingleException {}; {};
template <class T> template <class T>
class Set { class Set {
private: private:
T * T *pType pType; ;
public: public:
Set(); Set();
T& operator[] (int index) const; T& operator[] (int index) const;
}; };
Single Template Exception
Single Template Exception
160
C++ ve NESNEYE DAYALI PROGRAMLAMA 319
template <class T> template <class T>
class Set { class Set {
private: private:
T * T *pType pType; ;
public: public:
class class xEachException xEachException {}; {};
T& operator[] (int index) const; T& operator[] (int index) const;
}; };
// throw // throw xEachException xEachException(); ();
Each Template Exception
Each Template Exception
C++ ve NESNEYE DAYALI PROGRAMLAMA 320
Single Exception (declared outside the template class)
catch (xSingleException)
Each Exception (declared inside the template class)
catch (Set<int>::xEachException)
Catching Template Exceptions
Catching Template Exceptions
161
C++ ve NESNEYE DAYALI PROGRAMLAMA 321
The C++ standard includes some predefined
exceptions, in <stdexcept.h>
The base class is exception
Subclass logic_error is for errors which could
have been avoided by writing the program
differently
Subclass runtime_error is for other errors
Standard Exceptions
Standard Exceptions
C++ ve NESNEYE DAYALI PROGRAMLAMA 322
logic_error logic_error
Invalid_argument Invalid_argument domain_error domain_error length_error length_error out_of_range out_of_range
Logic Error Hierarchy
Logic Error Hierarchy
162
C++ ve NESNEYE DAYALI PROGRAMLAMA 323
runtime_error
overflow_error range_error
The idea is to use one of the specific classes
(e.g. range_error) to generate an exception
Runtime Error Hierarchy
Runtime Error Hierarchy
C++ ve NESNEYE DAYALI PROGRAMLAMA 324
// standard exceptions allow you to specify
// string information
throw overflow_error(Doing float division in function div);
// the exceptions all have the form:
class overflow_error : public runtime_error
{
public:
overflow_error(const string& what_arg)
: runtime_error(what_arg) {};
Data For Standard Exceptions
Data For Standard Exceptions
163
C++ ve NESNEYE DAYALI PROGRAMLAMA 325
catch (overflow_error)
{
cout << Overflow error << endl;
}
catch (exception& e)
{
cout << typeid(e).name() << : << [Link]() << endl;
}
Catching Standard Exceptions
Catching Standard Exceptions
C++ ve NESNEYE DAYALI PROGRAMLAMA 326
catch (exception& e)
Catches all classes derived from exception
If the argument was of type exception, it would be converted
from the derived class to the exception class
The handler gets a reference to exception as an argument,
so it can look at the object
More Standard Exception Data
More Standard Exception Data
164
C++ ve NESNEYE DAYALI PROGRAMLAMA 327
typeid is an operator which allows you to access the
type of an object at runtime
This is useful for pointers to derived classes
typeid overloads ==, !=, and defines a member
function name
if(typeid(*carType) == typeid(Ford))
cout << This is a Ford << endl;
typeid
typeid
C++ ve NESNEYE DAYALI PROGRAMLAMA 328
cout << typeid(*carType).name() << endl;
// If we had said:
// carType = new Ford();
// The output would be:
// Ford
So:
cout << typeid(e).name()
returns the name of the exception
typeid().name
typeid().name
165
C++ ve NESNEYE DAYALI PROGRAMLAMA 329
The class exception has a member function what
virtual char* what(); virtual char* what();
This is inherited by the derived classes
what() returns the character string specified in the throw
statement for the exception
[Link]()
[Link]()
throw throw
overflow_error(Doing overflow_error(Doing float division in function div); float division in function div);
cout cout << << typeid(e).name typeid(e).name() << : << () << : << [Link] [Link]() << () << endl endl; ;
C++ ve NESNEYE DAYALI PROGRAMLAMA 330
class xBadIndex : public runtime_error {
public
xBadIndex(const char *what_arg = Bad Index)
: runtime_error(what_arg) {}
};
// we inherit the virtual function what
// default supplementary information character string
Deriving New exception Classes
Deriving New exception Classes
166
C++ ve NESNEYE DAYALI PROGRAMLAMA 331
template <class T>
class Array{
private:
T *data ;
int Size ;
public:
Array(void);
Array(int);
class eNegativeIndex{};
class eOutOfBounds{};
class eEmptyArray{};
T& operator[](int) ;
};
C++ ve NESNEYE DAYALI PROGRAMLAMA 332
template <class T>
Array<T>::Array(void){
data = NULL ;
Size = 0 ;
}
template <class T>
Array<T>::Array(int size){
Size = size ;
data = new T[Size] ;
}
167
C++ ve NESNEYE DAYALI PROGRAMLAMA 333
template <class T>
T& Array<T>::operator[](int index){
if( data == NULL ) throw eEmptyArray() ;
if(index < 0) throw eNegativeIndex() ;
if(index >= Size) throw eOutOfBounds() ;
return data[index] ;
}
C++ ve NESNEYE DAYALI PROGRAMLAMA 334
Array<int> a(10) ;
try{
int b = a[200] ;
}
catch(Array<int>::eEmptyArray){
cout << "Empty Array" ;
}
catch(Array<int>::eNegativeIndex){
cout << "Negative Array" ;
}
catch(Array<int>::eOutOfBounds){
cout << "Out of bounds" ;
}