1
Capitolo 6: Classi e astrazione dati
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Introduzione
Definizione delle strutture
Accedere ai membri
Implementare un astract data type TIME con una classe
Scope della classe e accesso ai membri
Separare l’interfaccia dall’implementazione
Controllare l’accesso ai membri
Funzioni di accesso e di utility
Inizializzare gli oggetti: costruttori
Distruttori
Quando sono chiamati costruttori e distruttori
Usare dati membro e funzioni membro
Una trappola: ritornare una reference a una dato membro privato
Assegnamento di default per copia
Riusabilità del software
 2000 Prentice Hall, Inc. All rights reserved.
2
1.
Introduzione
Object-oriented programming (OOP)
– incapsula dati (attributi) e funzioni in packages chiamati
classi
Information hiding
– dettagli implementativi nascosti nelle classi
Classi
– sono le unità standard di programmazione
– una classe è un modello riutilizzabile
– gli oggetti sono istanziati (creati) a partire dalle classi
 2000 Prentice Hall, Inc. All rights reserved.
3
2.
Definizione delle strutture
Structures
– Tipo di dato aggregato, costruito usando elementi di altro
tipo
struct Time {
Structure tag
int hour;
int minute;
int second;
};
Structure members
– membri della stessa struttura devono avere un nome unico
– strutture diverse possono contenere membri con lo stesso
nome
– ogni definizione di struttura deve finire con il punto e virgola
 2000 Prentice Hall, Inc. All rights reserved.
4
Strutture self-referential
– contengono un membro che è puntatore alla stessa structure
type
– usate per liste linkate, code, stack, alberi.
struct
– crea un nuovo tipo di dato che è usato per dichiarare
variabili (come al solito)
Time timeObject, timeArray[10];
Time *timePtr, &timeRef = timeObject;
 2000 Prentice Hall, Inc. All rights reserved.
5
3.
Accedere ai membri
• Operatori di accesso ai membri sono:
– Dot (.) per strutture e oggetti
– Arrow (->) per puntatori
– Per stampare hour di timeObject:
cout << timeObject.hour;
oppure
timePtr = &timeObject;
cout << timePtr->hour;
– timePtr->hour è uguale a (*timePtr).hour
– * ha precedenza minore di.
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 6.1: fig06_01.cpp
// Create a structure, set its members, and print it.
#include <iostream>
1.1 Define prototypes
for the functions
struct Time {
// structure definition
int hour;
// 0-23
int minute;
// 0-59
int
second;
//type
0-59
2. Create
a struct data
};
Crea il tipo
Time con tre membri
integer: hour, minute e second.
void printMilitary( const Time & );
void printStandard( const Time & );
// set members to
dinnerTime.hour =
dinnerTime.minute
dinnerTime.second
Outline
1. Define the struct
using std::cout;
using std::endl;
int main()
{
Time dinnerTime;
6
// prototype
// prototype
2. Create a struct
data type
2.1 Set and print the
time
// variable of new type Time
valid values
18;
= 30;
= 0;
cout << "Dinner will be held at ";
printMilitary( dinnerTime );
cout << " military time,\nwhich is ";
printStandard( dinnerTime );
cout << " standard time.\n";
 2000 Prentice Hall, Inc. All rights reserved.
Dinner will be held at 18:30 military time,
which is 6:30:00 PM standard time.
32
// set members to invalid values
33
dinnerTime.hour = 29;
34
dinnerTime.minute = 73;
Outline
35
36
cout << "\nTime with invalid values: ";
37
printMilitary( dinnerTime );
38
cout << endl;
39
return 0;
Time with invalid values: 29:73
41
42 // Print the time in military format
43 void printMilitary( const Time &t )
44 {
46
cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":"
<< ( t.minute < 10 ? "0" : "" ) << t.minute;
47 }
48
49 // Print the time in standard format
50 void printStandard( const Time &t )
51 {
52
53
2.2 Set the time to an
invalid hour, then print
it
3. Define the functions
printMilitary and
printStandard
40 }
45
7
cout << ( ( t.hour == 0 || t.hour == 12 ) ?
12 : t.hour % 12 )
54
<< ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
55
<< ":" << ( t.second < 10 ? "0" : "" ) << t.second
56
<< ( t.hour < 12 ? " AM" : " PM" );
57 
} 2000 Prentice Hall, Inc. All rights reserved.
8
Dinner will be held at 18:30 military time,
which is 6:30:00 PM standard time.
Time with invalid values: 29:73
 2000 Prentice Hall, Inc. All rights reserved.
Outline
Program Output
9
4.
Implementare un abstract data type
TIME con una classe
Classi
– oggetti modello che hanno attributi (dati membri) e
comportamenti (funzioni membro)
– definite usando la keyword class
– corpo delineato dalle parentesi { e }
– la definizione termina con ;
1
2
3
4
5
6
7
8
9
10
11
class Time {
public:
Time();
void setTime( int, int, int );
void printMilitary();
void printStandard();
private:
int hour;
// 0 - 23
int minute;
// 0 - 59
int second;
// 0 - 59
};
 2000 Prentice Hall, Inc. All rights reserved.
Public:e Private: sono
specificatori di accesso ai membri.
setTime, printMilitary,
printStandard sono funzioni membro.
Time è il costruttore.
hour, minute, second
sono dati membro.
10
Specificatori di accesso ai menbri
– le classi possono limitare l’accesso ai propri dati e funzioni
membro
– tre tipi di accesso:
• public — accessibile da ogni altra funzione di ogni classe
• private — accessibile solo da funzioni membro della classe
• protected — simile a privato (discusso dopo)
Costruttore
– funzione membro speciale che inizializza i dati membro di un
oggetto di una classe
– non restituisce valori
– ha lo stesso nome della classe
 2000 Prentice Hall, Inc. All rights reserved.
11
Definizione e dichiarazione della classe
– una volta che una classe è definita, può essere usata come
tipo nella dichiarazione di un oggetto, array o puntatore
Time sunset,
arrayOfTimes[5],
*pointerToTime,
&dinnerTime = sunset;
Nota: il nome della
classe diventa il nuovo
specificatore di tipo.
 2000 Prentice Hall, Inc. All rights reserved.
// object of type Time
// array of Time objects
// pointer to a Time object
// reference to a Time object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Fig. 6.3: fig06_03.cpp
// Time class.
#include <iostream>
using std::cout;
using std::endl;
// Time abstract data type (ADT) definition
class Time {
public:
Time();
// constructor
void setTime( int, int, int ); // set hour, minute, second
void printMilitary();
// print military time format
void printStandard();
// print standard time format
private:
int hour;
// 0 – 23
int minute;
// 0 – 59
int second;
// 0 – 59
};
// Time constructor initializes each data member to zero.
// Ensures all Time objects start in a consistent state.
Time::Time() { hour = minute = second = 0; }
// Set a new Time value using military time. Perform validity
// checks on the data values. Set invalid values to zero.
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;

2000
Prentice Hall, Inc. All rights reserved.
}
12
Outline
1. Define a Time class
1.1 Define default
values for the time
Nota :: che precede i
nomi delle funzioni.
33
13
34 // Print Time in military format
Outline
35 void Time::printMilitary()
36 {
37
cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38
<< ( minute < 10 ? "0" : "" ) << minute;
39 }
40
1.2 Define the two
functions
printMilitary and
printstandard
41 // Print Time in standard format
42 void Time::printStandard()
43 {
44
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
45
<< ":" << ( minute < 10 ? "0" : "" ) << minute
46
<< ":" << ( second < 10 ? "0" : "" ) << second
47
<< ( hour < 12 ? " AM" : " PM" );
2. In main, create an
object of class Time
2.1Print the initial
(default) time
48 }
49
50 // Driver to test simple class Time
51 int main()
52 {
53
54
Time t;
// instantiate object t of class The
Timeinitial military time is 00:00
The initial standard time is 12:00:00 AM
55
cout << "The initial military time is ";
56
t.printMilitary();
57
cout << "\nThe initial standard time is ";
58
t.printStandard();
59
 2000 Prentice Hall, Inc. All rights reserved.
Nota come le funzioni
sono chiamate usando
l’operatore dot.
60
t.setTime( 13, 27, 6 );
61
cout << "\n\nMilitary time after setTime is ";
62
t.printMilitary();
63
cout << "\nStandard time after setTime is ";
64
t.printStandard();
65
14
2.2 Set and print the
time
Military time after setTime is 13:27
Standard time after setTime is 1:27:06 PM
// attempt invalid settings
66
t.setTime( 99, 99, 99 );
67
cout << "\n\nAfter attempting invalid settings:"
68
Outline
<< "\nMilitary time: ";
69
t.printMilitary();
70
cout << "\nStandard time: ";
71
t.printStandard();
72
cout << endl;
73
return 0;
74 }
2.4 Print the time
After attempting invalid settings:
Military time: 00:00
Standard time: 12:00:00 AM
The initial military time is 00:00
The initial standard time is 12:00:00 AM
Military time after setTime is 13:27
Standard time after setTime is 1:27:06 PM
After attempting invalid settings:
Military time: 00:00
Standard time: 12:00:00 AM
 2000 Prentice Hall, Inc. All rights reserved.
2.3 Set the time to an
invalid hour
Program Output
15
Distruttori
– funzioni con lo stesso nome della classe, precedito da ~
– non possono ricevere argomenti e non sono soggette ad
overloading
Operatore :: (binary scope resolution)
– combina il nome delle classi con il nome delle funzioni membro
– classi diverse possono avere funzioni membro con lo stesso nome
Formato per definire funzioni membro
ReturnType ClassName::MemberFunctionName( ){
…
}
 2000 Prentice Hall, Inc. All rights reserved.
16
Se una funzione membro è definita dentro la classe
– l’operatore di scope resolution e il nome della classe non
sono richiesti
– definire una funzione fuori o dentro una classe non cambia il
suo essere public o private
Le Classi incoraggiano il riuso del software
– l’ereditarietà consente di derivare nuove classi dalle vecchie
 2000 Prentice Hall, Inc. All rights reserved.
17
5
Class Scope e accesso ai membri
Scope della classe
– dati membro e funzioni membro
Scope del file
– funzioni non-member
Nello scope
– i membri (chiamati per nome) sono accessibili da tutte le
funzioni membro
Fuori dallo scope
– i membri sono chiamati per nome, per reference, con un
puntatore
 2000 Prentice Hall, Inc. All rights reserved.
18
Scope delle funzioni
– le variabili conoscono solo le funzioni nelle quali sono
definite
– le variabili sono distrutte dopo la chiusura delle funzione in
cui sono definite
Accesso ai membri di una classe
– come per le strutture
– Dot (.) per gli oggetti e arrow (->) per i puntatori
t.hour è l’elemento hour di t
TimePtr->hour è l’elemento hour
 2000 Prentice Hall, Inc. All rights reserved.
1 // Fig. 6.4: fig06_04.cpp
2 // Demonstrating the class member access operators . and ->
3 //
4
5
6
7
8
9
10
19
Outline
// CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
#include <iostream>
E’ raro
1. Class definition
using std::cout;
using std::endl;
2. Create an object of
the class
avere variabili
membro public.
// Simple class Count
definition
class1. Class
Count
{
public:
2. Create an object of the class
int x;
2.1 Assign a value to the object. Print the value using the dot operator
void print() { cout << x << endl; }
}; 2.2 Set a new value and print it using a reference
11
12
13
14
15
16
17 int main()
18 {
19
20
21
22
23
Di solito solo le
funzioni membro
sono public; così il 2.1 Assign a value to
massimo dell’inform the object. Print the
value using the dot
è hidden.
operator
Count counter,
// create counter object
*counterPtr = &counter, // pointer to counter
&counterRef = counter; // reference to counter
cout << "Assign 7 to x and print using the object's name: ";
24
counter.x = 7;
// assign 7 to data member x
25
counter.print();
// call member function print
26
27
cout << "Assign 8 to x and print using a reference: ";
28
counterRef.x = 8;
// assign 8 to data member x
29
counterRef.print(); // call member function print
30  2000 Prentice Hall, Inc. All rights reserved.
2.2 Set a new value
and print it using a
reference
31
cout << "Assign 10 to x and print using a pointer: ";
32
counterPtr->x = 10;
33
counterPtr->print(); // call member function print
34
return 0;
// assign 10 to data member x
35 }
Assign 7 to x and print using the object's name: 7
Assign 8 to x and print using a reference: 8
Assign 10 to x and print using a pointer: 10
 2000 Prentice Hall, Inc. All rights reserved.
20
Outline
2.3 Set a new value
and print it using a
pointer
Program Output
21
6
Separare interfaccia e implementazione
Rende più semplice modificare i programmi
Header files
– contengono definizioni di classi e prototipi delle funzioni
Source-code files
– contengono le definizioni delle funzioni membro
 2000 Prentice Hall, Inc. All rights reserved.
1
// Fig. 6.5: classe.h
2
// Declaration of the Time class.
3
// Member functions are defined in time1.cpp
22
Outline
4
5
// prevent multiple inclusions of header file
6
#ifndef TIME1_H
7
#define TIME1_H
8
9
// Time abstract data type definition
10 class Time {
11 public:
// constructor
1. Using the same
Time class as before,
create a header file
Dot ( . ) rimpiazzato con underscore ( _ ) nel
nome del file.
Se time1.h (TIME1_H) non definito
(#ifndef) allora è caricato (#define
TIME1_H).
Se TIME1_H è già definito, allora tutto
fino a #endif è ignorato.
12
Time();
13
void setTime( int, int, int ); // set hour, minute, second
14
void printMilitary();
// print military time format
15
void printStandard();
// print standard time format
16 private:
17
int hour;
// 0 - 23
18
int minute;
// 0 - 59
19
int second;
// 0 - 59
20 };
21
22 #endif
 2000 Prentice Hall, Inc. All rights reserved.
Questo consente di non leggere un file
header più volte.
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Fig. 6.5: time1.cpp
// Member function definitions for Time class.
#include <iostream>
using std::cout;
#include “classe.h"
Si usa #include per
caricare l’header file
// Time constructor initializes each data member to zero.
// Ensures all Time objects start in a consistent state.
Time::Time() { hour = minute = second = 0; }
// Set a new Time value using military time. Perform validity
// checks on the data values. Set invalid values to zero.
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;
}
// Print Time in military format
void Time::printMilitary()
{
cout << ( hour < 10 ? "0" : "" ) << hour << ":"
<< ( minute < 10 ? "0" : "" ) << minute;
}
// Print time in standard format
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
<< ":" << ( minute < 10 ? "0" : "" ) << minute
<< ":" << ( second < 10 ? "0" : "" ) << second
<< ( hour < 12 ? " AM" : " PM" );

2000
Prentice
Hall, Inc. All rights reserved.
}
23
Outline
2. Create a source
code file
2.1 Load the header
file to get the class
definitions
2.2. Define the
member functions of
the class
Il file sorgente contiene
le definizioni delle
funzioni.
24
7
Controllare l’accesso ai membri
public
– dati e funzioni membro sono accessibili
private
– modalità di default
– dati accessibili solo dalle funzioni membro e dalle classi
friends
– membri private accessibili attraverso la classe interfaccia
public usando funzioni membro public
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 6.6: fig06_06.cpp
// Demonstrate errors resulting from attempts
// to access private class members.
#include <iostream>
25
Outline
1. Load header file for
Time class
using std::cout;
#include "time1.h"
2. Create an object of
class Time
int main()
{
Time t;
// Error: 'Time::hour' is not accessible
t.hour = 7;
// Error: 'Time::minute' is not accessible
cout << "minute = " << t.minute;
return 0;
2.1 Attempt to set a
private variable
tentativo di modificare la variabile
2.2private.
Attempt to access a
hour, che è un membro
private variable
tentativo di accedere alla variabile
minute.
}
Compiling...
Fig06_06.cpp
D:\Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private
member declared in class 'Time'
D:\Fig6_06\time1.h(18) : see declaration of 'hour'
D:\Fig06_06.cpp(18) : error C2248: 'minute' : cannot access private
member declared in class 'Time'
D:\time1.h(19) : see declaration of 'minute'
Error executing cl.exe.
test.exe - 2 error(s), 0 warning(s)
 2000 Prentice Hall, Inc. All rights reserved.
Program Output
26
8 Funzioni di accesso e di utility
Utility functions
– funzioni private che supportano le operazioni di funzioni
public
– non sono pensate per essere usate direttamente dagli utenti
Access functions
– funzioni public che leggono/scrivono dati o testano
condizioni
– consentono a funzioni public di testare dati private
Esempio
– inserire le vendite mensili e dare in output il totale
– mostro solo le access functions
 2000 Prentice Hall, Inc. All rights reserved.
87 // Fig. 6.7: fig06_07.cpp
27
Outline
88 // Demonstrating a utility function
89 // Compile with salesp.cpp
90 #include "salesp.h"
crea un oggetto s, istanza
della classe SalesPerson
91
92 int main()
93 {
94
SalesPerson s;
// create SalesPerson object s
96
s.getSalesFromUser();
// note simple sequential code
97
s.printAnnualSales();
// no control structures in main
98
return 0;
95
99 }
OUTPUT
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
Enter sales
amount
amount
amount
amount
amount
amount
amount
amount
amount
amount
amount
amount
for
for
for
for
for
for
for
for
for
for
for
for
month
month
month
month
month
month
month
month
month
month
month
month
1: 5314.76
2: 4292.38
3: 4589.83
4: 5534.03
5: 4376.34
6: 5698.45
7: 4439.22
8: 5893.57
9: 4909.67
10: 5123.45
11: 4024.97
12: 5923.92
The total annual sales are: $60120.59
 2000 Prentice Hall, Inc. All rights reserved.
1. Load header file
and compile with the
file that contains the
function definitions
2. Create an object
2.1 Use the object’s
member functions to
and print
sales e
access get
functions
per prelevare
stampare i dati
(getSalesFromUser e
printAnnualSales).
qui c’èProgram
una utilityOutput
function che
calcola le vendite totali, ma
l’utente non vede le chiamate.
main() è semplice – no
strutture di controllo, solo
chiamate.
28
9
Inizializzare gli oggetti: costruttori
Costruttori
– inizializzano i membri della classe
– stesso nome della classe e no return type
– le variabili membro possono essere inizializzate dal costruttore
o anche dopo
Passare argomenti al costruttore
– quando è dichiarato un oggetto di una classe, devono essere
forniti dati di inizializzazione
– formato di dichiarazione con inizializzatori:
Class-type ObjectName( value1,value2,…);
– argomenti di default possono essere specificati nel prototipo
del costruttore
 2000 Prentice Hall, Inc. All rights reserved.
1
// Fig. 6.8: time2.h
29
Outline
2 // Declaration of the Time class.
3
// Member functions are defined in time2.cpp
1. Define class Time
and its default values
4
5
// preprocessor directives that
6
// prevent multiple inclusions of header file
7
#ifndef TIME2_H
8
#define TIME2_H
9
10 // Time abstract data type definition
11 class Time {
12 public:
13
Time( int = 0, int = 0, int = 0 );
14
void setTime( int, int, int ); // set hour, minute, second
15
void printMilitary();
// print military time format
16
void printStandard();
// print standard time format
17 private:
18
int hour;
// 0 - 23
19
int minute;
// 0 - 59
20
int second;
// 0 - 59
21 };
22
23 #endif
 2000 Prentice Hall, Inc. All rights reserved.
// default constructor
Nota il setting di default per
le tre variabili membro; è
fatto nel prototipo del
costruttore.
Non ci sono i nomi delle
variabili; i defalt sono
applicati in ordine.
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Fig. 6.8: fig06_08.cpp
// Demonstrating a default constructor
// function for class Time.
#include <iostream>
30
Outline
2. Create objects
using default
Se non sono specificati sufficienti valori, i valori
arguments
più a destra sono di default.
Nota come gli oggetti sono inizializzati.
using std::cout;
using std::endl;
#include "time2.h"
int main()
{
Time t1,
//
t2(2),
//
t3(21, 34),
//
t4(12, 25, 42), //
t5(27, 74, 99); //
2.1 Print the objects
all arguments defaulted
minute and second defaulted
second defaulted
all values specified
all bad values specified
cout << "Constructed with:\n"
<< "all arguments defaulted:\n
t1.printMilitary();
cout << "\n
";
t1.printStandard();
";
cout << "\nhour specified; minute and second defaulted:"
<< "\n
";
t2.printMilitary();
cout << "\n
";
t2.printStandard();
cout << "\nhour and minute specified; second defaulted:"
<< "\n
";
 2000
Prentice
Hall,
Inc.
All rights reserved.
t3.printMilitary();
94
cout << "\n
";
95
t3.printStandard();
96
97
cout << "\nhour, minute, and second specified:"
98
<< "\n
";
99
t4.printMilitary();
100
cout << "\n
";
101
t4.printStandard();
102
103
cout << "\nall invalid values specified:"
104
<< "\n
";
105
t5.printMilitary();
106
cout << "\n
";
107
t5.printStandard();
108
cout << endl;
109
110
return 0;
111 }
OUTPUT
Constructed with:
all arguments defaulted:
00:00
12:00:00 AM
hour specified; minute and second defaulted:
02:00
2:00:00 AM
hour and minute specified; second defaulted:
21:34
9:34:00 PM
hour, minute, and second specified:
12:25
12:25:42 PM
all invalid values specified:
00:00
12:00:00
AM Hall, Inc. All rights reserved.

2000 Prentice
31
Outline
2.1 (continued) Print
the objects.
Se solo hour è
specificato,
Program Output
minute e
second sono di
default uguali a 0.
32
10
Distruttori
– sono funzioni membro della classe
– effettuano “housekeeping” prima che il sistema riacquisti il
controllo sulla memoria assegnata all’oggetto
– il nome è tilde (~) seguito dal nome della classe
(i.e., ~Time)
– Non riceve parametri, non ritorna valori
– Un solo distruttore per classe (no overloading)
 2000 Prentice Hall, Inc. All rights reserved.
33
11
Quando sono chiamati costruttori e
distruttori
Oggetti statici locali
– costruttori chiamati quando l’esecuzione raggiunge il punto
in cui un oggetto è definito
– distruttori chiamati quando main termina o la funzione
exit è chiamata
– distruttori non chiamati se il programma termina con abort
 2000 Prentice Hall, Inc. All rights reserved.
1
// Fig. 6.9: create.h
2
// Definition of class CreateAndDestroy.
34
Outline
3 // Member functions defined in create.cpp.
4
#ifndef CREATE_H
5
#define CREATE_H
1. Create a header file
6
7
class CreateAndDestroy {
8
public:
9
10
CreateAndDestroy( int );
// constructor
~CreateAndDestroy();
// destructor
11 private:
12
int data;
13 };
14
15 #endif
 2000 Prentice Hall, Inc. All rights reserved.
1.1 Include function
prototypes for the
destructor and
constructor
16 // Fig. 6.9: create.cpp
35
17 // Member function definitions for class CreateAndDestroy
18 #include <iostream>
Outline
2. Load the header file
19
2.1 Modify the
constructor and
destructor
20 using std::cout;
21 using std::endl;
22
23 #include "create.h"
24
25 CreateAndDestroy::CreateAndDestroy( int value )
26 {
entrambi stampano il dato se chiamati.
27
data = value;
28
cout << "Object " << data << "
constructor";
29 }
30
31 CreateAndDestroy::~CreateAndDestroy()
32
{ cout << "Object " << data << "
 2000 Prentice Hall, Inc. All rights reserved.
destructor " << endl; }
33 // Fig. 6.9: fig06_09.cpp
34 // Demonstrating the order in which constructors and
35 // destructors are called.
36
37
38
39
40
41
42
#include <iostream>
43
44
45
46
47
48
49
void create( void );
50
51
52
53
54
55
Outline
3. Create multiple
objects of varying
types
using std::cout;
using std::endl;
#include "create.h"
// prototype
CreateAndDestroy first( 1 );
int main()
{
cout << "
36
// global object
(global created before main)" << endl;
CreateAndDestroy second( 2 );
// local object
cout << "
(local automatic in main)" << endl;
static CreateAndDestroy third( 3 ); // local object
cout << "
(local static in main)" << endl;
56
57
create(); // call function to create objects
58
59
CreateAndDestroy fourth( 4 );
// local object
60
cout << "
(local automatic in main)" << endl;
61
return 0;
62 
} 2000 Prentice Hall, Inc. All rights reserved.
63
64 // Function to create objects
65 void create( void )
66 {
67
68
69
70
71
72
73
74
75 }
OUTPUT
Object
Object
Object
Object
Object
Object
Object
Object
Object
Object
Object
Object
Object
Object
37
Outline
CreateAndDestroy fifth( 5 );
cout << "
(local automatic in create)" << endl;
static CreateAndDestroy sixth( 6 );
cout << "
(local static in create)" << endl;
CreateAndDestroy seventh( 7 );
cout << "
(local automatic in create)" << endl;
1
2
3
5
6
7
7
5
4
4
2
6
3
1
constructor
constructor
constructor
constructor
constructor
constructor
destructor
destructor
constructor
destructor
destructor
destructor
destructor
destructor
(global created before main)
(local automatic in main)
(local static in main)
(local automatic in create)
(local static in create)
(local automatic in create)
(local automatic in main)
 2000 Prentice Hall, Inc. All rights reserved.
Program Output
Nota come l’ordine di chamata di
costruttori e distruttori dipenda dal
tipo della variabile (automatic,
global e static).
38
12
Usare dati membro e funzioni membro
Member functions
– consentono di scrivere e leggere i valori dei dati membro privati
(set e get)
– esempio: Adjusting a customer’s bank balance
• il dato membro balance (private) di una classe
BankAccount potrebbe essere modificato con l’uso di una
funzione membro computeInterest
• una funzione membro che setta il dato membro interestRate
può essere chiamata setInterestRate; una funzione membro
che titorna il dato interestRate può essere chiamata
getInterestRate
– set e get functions non rendono public dati private
– una funzione set deve assicurare che il valore sia valido
 2000 Prentice Hall, Inc. All rights reserved.
39
13 Una trappola: ritornare una reference a
un dato membro privato
Reference a un oggetto
– è un alias per il nome dell’oggetto
– può essere usata a sinistra di un assegnamento
– può ricevere un valore, che cambia anche l’oggetto originale
Restituire references
– funzioni membro public possono restituire references
non-const a dati membro private (da evitare, rompono
l’incapsulamento)
 2000 Prentice Hall, Inc. All rights reserved.
1
// Fig. 6.11: time4.h
2
// Declaration of the Time class.
40
Outline
3 // Member functions defined in time4.cpp
4
1. Define class
5
// preprocessor directives that
6
// prevent multiple inclusions of header file
7
#ifndef TIME4_H
8
#define TIME4_H
9
10 class Time {
Nota come la funzione membro
badSetHour ritorna una reference
(int & è il tipo ritornato).
11 public:
12
Time( int = 0, int = 0, int = 0 );
13
void setTime( int, int, int );
14
int getHour();
15
int &badSetHour( int );
// DANGEROUS reference return
16 private:
17
int hour;
18
int minute;
19
int second;
20 };
21
22 #endif
 2000 Prentice Hall, Inc. All rights reserved.
1.1 Function
prototypes
1.2 Member variables
23 // Fig. 6.11: time4.cpp
24 // Member function definitions for Time class.
25 #include "time4.h"
26
27
28
29
30
31
32
// Constructor function to initialize private data.
// Calls member function setTime to set variables.
// Default values are 0 (see class definition).
Time::Time( int hr, int min, int sec )
{ setTime( hr, min, sec ); }
33
34
35
36
37
38
39
// Set the values of hour, minute, and second.
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;
}
40
41
42
43
44
45
// Get the hour value
int Time::getHour() { return hour; }
// POOR PROGRAMMING PRACTICE:
// Returning a reference to a private data member.
46 int &Time::badSetHour( int hh )
47 {
48
hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
49
50
return hour; // DANGEROUS reference return
51 }
 2000 Prentice Hall, Inc. All rights reserved.
41
Outline
1. Load header
1.1 Function
definitions
badSetHour ritorna
una reference alla
variabile membro
private hour.
Cambiare questa reference
altera anche il valore di
hour.
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Fig. 6.11: fig06_11.cpp
// Demonstrating a public member function that
// returns a reference to a private data member.
// Time class has been trimmed for this example.
#include <iostream>
using std::cout;
using std::endl;
#include "time4.h"
42
Outline
1.2 Declare reference
dichiaro l’oggetto t di classe Time 2. Change data using a
reference
e la reference hourRef, a cui è
assegnata la reference restituita dalla
chiamata t.badSetHour(20). 3. Output results
int main()
{
Time t;
int &hourRef = t.badSetHour( 20 );
Hour before modification: 20
cout << "Hour before modification: " << hourRef;
hourRef = 30; // modification with invalid value
cout << "\nHour after modification: " << t.getHour();
alias usato per settare il
valore di hour a 30
(invalido).
Hour after modification: 30
// Dangerous: Function call that returns
// a reference can be used as an lvalue!
t.badSetHour(12) = 74;
chiamata di funzione usata come
cout << "\n\n*********************************\n"
un lvalue e a cui è assegnato il
<< "POOR PROGRAMMING PRACTICE!!!!!!!!\n"
valore 74 (invalido).
<< "badSetHour as an lvalue, Hour: "
<< t.getHour()
<< "\n*********************************" << endl;
*********************************
return 0;
}
 2000 Prentice Hall, Inc. All rights reserved.
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************
43
Hour before modification: 20
Hour after modification: 30
*********************************
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************
HourRef è usato per assegnare
ad hour un valere invalido.
Normalmente la funzione
setbadSetHour non deve
poter fare questo.
Tutto accade perchè è restituita
una reference.
 2000 Prentice Hall, Inc. All rights reserved.
Outline
Program Output
44
14.
Assegnamento di default per copia
Assegnare oggetti
– un oggetto può essere assegnato a un altro oggetto dello
stesso tipo usando =
– Copia membro a membro
Gli oggetti possono essere
– passati come argomenti di funzioni
– restituiti da funzioni (default call-by-value)
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 6.12: fig06_12.cpp
// Demonstrating that class objects can be assigned
// to each other using default memberwise copy
#include <iostream>
45
Outline
1. Define class
using std::cout;
using std::endl;
// Simple Date class
class Date {
public:
Date( int = 1, int = 1, int = 1990 ); // default constructor
void print();
private:
int month;
int day;
int year;
};
// Simple Date constructor with no range checking
Date::Date( int m, int d, int y )
{
month = m;
day = d;
year = y;
}
// Print the Date in the form mm-dd-yyyy
void Date::print()
{ cout << month << '-' << day << '-' << year; }
 2000 Prentice Hall, Inc. All rights reserved.
1.1 Define member
functions
31
32 int main()
33 {
46
Outline
34
35
36
37
38
39
40
Date date1( 7, 4, 1993 ), date2;
// d2 defaults to 1/1/90
41
42
43
44
45
46
47 }
date2 = date1;
// assignment by default memberwise copy
cout << "\n\nAfter default memberwise copy, date2 = ";
date2.print();
date2 = date1, tutti i
cout << endl;
cout << "date1 = ";
date1.print();
cout << "\ndate2 = ";
date2.print();
2. Create Date objects
2.1 Memberwise copy
3. Print values
membri sono copiati.
return 0;
date1 = 7-4-1993
date2 = 1-1-1990
After default memberwise copy, date2 = 7-4-1993
 2000 Prentice Hall, Inc. All rights reserved.
Program Output
47
15.
Riusabilità del software
– implementazione di classi utili
– le librerie di classi consentono di costruire programmi da ciò
che già esiste, è definito bene, testato, documentato,
portabile, disponibile
– Accelera lo sviluppo di software di alta qualità
 2000 Prentice Hall, Inc. All rights reserved.
Scarica

Document