Post on 21-Dec-2015
2003 Prentice Hall, Inc. All rights reserved.
1
6.1 Introduction
• Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior) into
packages called classes
• Information hiding – Class objects communicate across well-defined interfaces
– Implementation details hidden within classes themselves
• User-defined (programmer-defined) types: classes– Data (data members)
– Functions (member functions or methods)
– Similar to blueprints – reusable
– Class instance: object
Structured Data Types
struct = an abstract data type
with a fixed number of
components that are accessed by
name, not by index.
2003 Prentice Hall, Inc. All rights reserved.
3
6.2 Structure Definitions
• Structures – Aggregate data types built using elements of other types
struct Time {
int hour;
int minute;
int second;
};
• Structure member naming– In same struct: must have unique names
– In different structs: can share name
• struct definition must end with semicolon
Structure tag
Structure members
2003 Prentice Hall, Inc. All rights reserved.
4
6.2 Structure Definitions
• Self-referential structure – Structure member cannot be instance of enclosing struct– Structure member can be pointer to instance of enclosing struct (self-referential structure)
• Used for linked lists, queues, stacks and trees
• struct definition– Creates new data type used to declare variables– Structure variables declared like variables of other types– Examples:
• Time timeObject;• Time timeArray[ 10 ]; • Time *timePtr;• Time &timeRef = timeObject;
2003 Prentice Hall, Inc. All rights reserved.
5
6.3 Accessing Structure Members
• Member access operators– Dot operator (.) for structure and class members
– Arrow operator (->) for structure and class members via pointer to object
– Print member hour of timeObject:
cout << timeObject.hour;
Can Assign Aggregate Values in the declaration
Date myBirth = {2, 29, 1963};
Date today = {11, 25, 1999};
Date bill_Date = {3, 25, 2001};
Date lily_Bday = {1, 20, 1995};
Assigning Values
myBirth.month = 2;
myBirth.day = 29;
myBirth.year = 1963;
bill_Date.month = 3;bill_Date.day = 25;
lily_Bday.year = 1995;today.month = 4;
* *
instance of Date
member of myBirth instance
Alternate assignments:
struct {
int month;
int day;
int year;
} mybirth,billday,today;
Variables of type struct
struct Date {
int month;
int day;
int year;
};
Date mybirth, billday,today;
2003 Prentice Hall, Inc. All rights reserved.
Structures as Arguments
// in a prototype// in a prototype
int Overdue(Date, int);
* * * *
// in a function call// in a function callOverdue(today, bill_Date.year);
// in a function header// in a function headerint Overdue(Date now, int purchased)
2003 Prentice Hall, Inc. All rights reserved.
Aggregate Operations
Operation Arrays Structs
I/O No (except strings) No
Assignment No Yes
Arithmetic No No
Comparison No NoParameter pass. Ref. only Either
value or ref.
Funct. return value No Yes
2003 Prentice Hall, Inc. All rights reserved.
11
6.4 Implementing a User-Defined Type Time with a struct
• Default: structures passed by value – Pass structure by reference
• Avoid overhead of copying structure
• C-style structures – No “interface”
• If implementation changes, all programs using that struct must change accordingly
– Cannot print as unit• Must print/format member by member
– Cannot compare in entirety• Must compare member by member
2003 Prentice Hall, Inc.All rights reserved.
Outline12
fig06_01.cpp(1 of 3)
1 // Fig. 6.1: fig06_01.cpp2 // Create a structure, set its members, and print it.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setfill;11 using std::setw;12 13 // structure definition 14 struct Time { 15 int hour; // 0-23 (24-hour clock format)16 int minute; // 0-59 17 int second; // 0-59 18 19 }; // end struct Time 20 21 void printUniversal( const Time & ); // prototype22 void printStandard( const Time & ); // prototype23
Define structure type Time with three integer members.
Pass references to constant Time objects to eliminate copying overhead.
2003 Prentice Hall, Inc.All rights reserved.
Outline13
fig06_01.cpp(2 of 3)
24 int main()25 {26 Time dinnerTime; // variable of new type Time 27 28 dinnerTime.hour = 18; // set hour member of dinnerTime 29 dinnerTime.minute = 30; // set minute member of dinnerTime30 dinnerTime.second = 0; // set second member of dinnerTime31 32 cout << "Dinner will be held at ";33 printUniversal( dinnerTime );34 cout << " universal time,\nwhich is ";35 printStandard( dinnerTime ); 36 cout << " standard time.\n";37 38 dinnerTime.hour = 29; // set hour to invalid value 39 dinnerTime.minute = 73; // set minute to invalid value40 41 cout << "\nTime with invalid values: ";42 printUniversal( dinnerTime );43 cout << endl;44 45 return 0; 46 47 } // end main48
Use dot operator to initialize structure members.
Direct access to data allows assignment of bad values.
2003 Prentice Hall, Inc.All rights reserved.
Outline14
fig06_01.cpp(3 of 3)
fig06_01.cppoutput (1 of 1)
49 // print time in universal-time format50 void printUniversal( const Time &t )51 {52 cout << setfill( '0' ) << setw( 2 ) << t.hour << ":"53 << setw( 2 ) << t.minute << ":" 54 << setw( 2 ) << t.second;55 56 } // end function printUniversal57 58 // print time in standard-time format59 void printStandard( const Time &t )60 {61 cout << ( ( t.hour == 0 || t.hour == 12 ) ? 62 12 : t.hour % 12 ) << ":" << setfill( '0' )63 << setw( 2 ) << t.minute << ":" 64 << setw( 2 ) << t.second 65 << ( t.hour < 12 ? " AM" : " PM" );66 67 } // end function printStandard
Dinner will be held at 18:30:00 universal time,
which is 6:30:00 PM standard time.
Time with invalid values: 29:73:00
Use parameterized stream manipulator setfill.
Use dot operator to access data members.
Arrays of Structures
struct Salaried{ char dept[5];
int salary;
int vac_days;};
// array of 20 elements, each of type Salaried
Salaried emp[20];
Arrays of Structures
emp[0].dept = “Purc”;
emp[0].salary = 34560;
emp[0].vac_days = 14;...
emp[2].salary = 32100;
emp[2].dept = “Ship”;
emp[2].vac_days = 10;
…emp[19].dept = “Acct”;
emp[19].salary = 22500;
emp[19].vac_days = 12;
Arrays of Structuresstruct Payroll{
int id;char name[15];double payrate;
};
// an array of 3 records of type PayrollPayroll employee[3];
Arrays of Structures
// load array -- there are other ways to load the array
Payroll employee[3] = { {11, “Mickey”, 7.25}, {12, “Minny”, 6.50}, {13, “Donald”, 9.00} };
// display array
for(ndx = 0; ndx < 3; ndx++)cout << ‘\n’ << employee[ndx].id << setw(20) << employee[ndx].name << setw(20) << employee[ndx].payrate;
Arrays of Structures
int main(){ //declare array of 3 records of type Payroll // and initialize the first record Payroll employee[3] = { 11, “Mickey", 7.25 };
loadarray(employee); // calls showarray(employee);
cout << endl<<endl; // for formatting} // end main()
Arrays of Structures
// load array - data typically entered via file inputvoid loadarray(Payroll staff[3])
{ // begin at 1 because [0] already entered for(int ndx = 1; ndx < 3; ndx++) { cout << "Enter the ID, name, and pay rate: "; cin >> staff[ndx].id >> staff[ndx].name >> staff[ndx].payrate; cout << endl; }}
Nested Structuresstruct Date
{ int month;
int day;
int year; };
struct vital_Data
{ char name[15];
char owner[10];
int ID;
Date birth; // Date must be previously defined
double strength;
};
*
Nested Structures
vital_Data Digimon; // declaration of an object// declaration of an object
// assignments of data to an object
strcpy(Digimon.name,“wormmon”);
strcpy(Digimon.owner ,“ken”);
Digimon.ID = 1234;
Digimon.birth.day= 10; // this is a struct
Digimon.evolution = 12.75;
#include <iostream>#include <iomanip>using namespace std;struct Employee{ int idNum; double payRate; double hours;};Employee getValues(); int main(){ Employee emp; emp = getValues(); cout << "\nThe employee id number is " << emp.idNum << "\nThe employee pay rate is $" << emp.payRate << "\nThe employee hours are " << emp.hours << endl; return 0;}
//return a struct
Employee getValues(){ Employee next; next.idNum = 6789; next.payRate = 16.25; next.hours = 38.0;return next;}
2003 Prentice Hall, Inc. All rights reserved.
24
Pointers to structures
– Print member hour of timeObject:
cout << timeObject.hour;
OR
timePtr = &timeObject; cout << timePtr->hour;
– timePtr->hour same as ( *timePtr ).hour• Parentheses required
– * lower precedence than .
Pointers to Structures
struct Employee{ int idNum; double payRate; double hours;}
Employee *pt;
(*pt).idnum pt->idnum
“the structure whose
address is in pt”
(*pt).payRate pt->payRate
(*pt).hours pt->hours
Alternate notation
Use:Declaration:
2003 Prentice Hall, Inc. All rights reserved.
26
Structures which include self referential pointers
• For linked lists
Self referential structures
The records are linked by including the address of the next record (I.e. a pointer).
struct Beers
{
char beername[10];
Beer *nextbeer;
}
Pointer to another structure
Main (){ Beer t1 = {“bud”}; Beer t2 = {“miller”}; Beer t3 = {“coors”}; Beer *first;
first = &t1;t1.nextbeer = &t2;t2.nextbeer = &t3;t3.nextbeer = NULL; //sets pointer to zero
cout << first->beername << t1.nextbeer -> name << t2.nextbeer->name;
Bud 0xff1 Miller 0xaf3 Coors \00xff1 0xaf3
t1 t2 t3
0xaaa
first0xaaa
Bud 0xff1 Miller 0xaf3 Coors \00xff1 0xaf3
t1 t2 t3
0xaaa
first0xaaa
first = first->nextbeer;cout <<first->beername<<endl;
first = first->nextbeer;cout <<first->beername<<endl;
first = first->nextbeer;cout <<first->beername<<endl;
\00xff1 0xaf3
****
4
p,x
7 NULL
q,y
el next
struct nodetype { int el; nodetype *next; };nodetype *p, *q, x,y,z;
p= &x;p->el = 4;q = &y;q->el = 7;q->next = NULL;p->next = q;cout << p->el << endl;cout << q->el << endl;p=p->next;cout <<p->el << endl;
q4
7 NULL
p
q4
7 NULL
p
***
Dynamic allocation
new reserves the number of bytes required by the requested data type and returns the address of the first reserved location or NULL if there is no memory
delete releases the block of bytes
(1) p = new nodetype;(2) q = p;(3) p->el = 4;(4) r = new nodetype;(5) r->el = 9;(6) s = new nodetype;(7) s->el = q->el + p->el;(8) p->next = r;(9) r->next = s;(10) r->el = 3.0;(11) s=p;(12) q = q->next;(13) q->el = 6.0;(14) q = q->next;(15) cout << p->el << endl;(16) cout << q->el << endl;(17) cout << r->el << endl;(18) cout << s->el << endl;
p q
4 | 9 |
r
13 |
s
s p q 4 | 3 |
r
8 |
s p 4 | 6 |
r q
8 |
q
s p 4 | 6 |
r
8 |
final
*****