+ All Categories
Home > Documents > C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows...

C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows...

Date post: 19-Jan-2016
Category:
Upload: gyles-short
View: 217 times
Download: 0 times
Share this document with a friend
Popular Tags:
60
C++ Structured Data and Classes
Transcript
Page 1: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

C++

Structured Data and Classes

Page 2: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Combining Data into Structures

• Structure: C++ construct that allows multiple variables to be grouped together

• Structure Declaration Format: struct structure name{type1 field1;type2 field2; …

typen fieldn;};

Page 3: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example struct Declaration

struct Student

{

int studentID;

string name;

short year;

double gpa;

};

structure tag

structure members

Notice the required

;

Page 4: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

4

struct examples• Example:

struct StudentInfo{int Id;int age;char Gender;double CGA; };

• Example:struct StudentGrade{char Name[15];char Course[9];int Lab[5];int Homework[3];int Exam[2];};

The “StudentGrade” structure has 5 members of

different array types.

The “StudentInfo” structure has 4 members

of different types.

Page 5: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

5

struct examples• Example:

struct BankAccount{char Name[15];int AcountNo[10];double balance;Date Birthday;

};

• Example:struct StudentRecord{

char Name[15];int Id;char Dept[5];char Gender;

};

The “StudentRecord” structure has 4

members.

The “BankAcount” structure has simple, array and structure

types as members.

Page 6: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

struct Declaration Notes

• struct names commonly begin with an uppercase letter

• Multiple fields of same type can be in a comma-separated list string name,

address;

Page 7: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Defining Structure Variables

• struct declaration does not allocate memory or create variables

• To define variables, use structure tag as type nameStudent s1; studentID

name

year

gpa

s1

Page 8: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example: structuresstruct date

{

int month;

int day;

int year;

};

struct date today, purchaseDate;

today.year = 2004;

today.month = 10;

today.day = 5;

Defines type struct date, with 3 fields of type int

The names of the fields are local in the context

of the structure.

A struct declaration defines a type: if not followed by a

list of variables it reserves no storage; it merely

describes a template or shape of a structure.

Defines 3 variables of

type struct date

Accesses fields of a variable of

type struct date

A member of a particular structure is referred to

in an expression by a construction of the

form structurename.member

Page 9: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

9

Page 10: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Structure definitionStructure definition

• To define a structure for student’s To define a structure for student’s informationinformation

typedef struct {

char [30] name;

int age;

} student;

Student s1, s2;Student s1, s2;

Page 11: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Structure usingStructure using

• When we use the structure data asWhen we use the structure data as

S1.age = 21;S1.age = 21;

S2.age = 20;S2.age = 20;

Strcpy(s1.name, “mohamed”);Strcpy(s1.name, “mohamed”);

Strcpy(s2.name, “ahmed”);Strcpy(s2.name, “ahmed”);

Page 12: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Accessing Structure Members

• Use the dot (.) operator to refer to members of struct variables

getline(cin, s1.name);

cin >> s1.studentID;

s1.gpa = 3.75;

• Member variables can be used in any manner appropriate for their data type

Page 13: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Displaying struct Members

• To display the contents of a struct variable, you must display each field separately, using the dot operator

Wrong: cout << s1; // won’t work!Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa;

Page 14: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Initializing a Structure

• Cannot initialize members in the structure declaration, because no memory has been allocated yet

struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; };

Page 15: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example• Write a program which accepts from the user via

the keyboards, and the following data items:• it_number – integer value,• name – string, up to 20 characters,• amount – integer value.• Your program will store this data for 3 persons

and display each record is proceeded by the record number.

15

Page 16: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Comparing struct Variables

• Cannot compare struct variables directly:

if (stu1 == stu2) // won’t work

• Instead, must compare on a member basis:

if (stu1.studentID == stu2.studentID)

Page 17: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Initializing a Structure (continued)

• Structure members are initialized at the time a structure variable is created

• Can initialize a structure variable’s members with either– an initialization list

– a constructor

Page 18: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Using an Initialization List

• An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members

{12, 6, 3} // initialization list // with 3 values

Page 19: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

More on Initialization Lists

• Order of list elements matters: First value initializes first data member, second value initializes second data member, etc.

• Elements of an initialization list can be constants, variables, or expressions

{12, W, L/W + 1} // initialization list // with 3 items

Page 20: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Initialization List Example

Structure Declaration Structure Variable

struct Dimensions{ int length, width, height;};

Dimensions box = {12,6,3};

box

length 12

width 6

height 3

Page 21: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Partial Initialization

• Can initialize just some members, but cannot skip over members

Dimensions box1 = {12,6}; //OKDimensions box2 = {12,,3}; //illegal

Page 22: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Problems with Initialization List

• Can’t omit a value for a member without omitting values for all following members

• Does not work on most modern compilers if the structure contains any string objects – Will, however, work with C-string members

Page 23: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Examples

//Create a box with all dimensions given Dimensions box4(12, 6, 3);

//Create a box using default value 1 for //height Dimensions box5(12, 6);

//Create a box using all default values Dimensions box6;

Omit () when no arguments

are used

Page 24: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example

• Write a car struct that has the following fields: YearModel (int), Make (string), and Speed (int).

• The program has function assign_data ( ) accelerate ( ) which add 5 to the speed each time it is called, break () which subtract 5 from speed each time it is called, and display () to print out the car’s information.

Page 25: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Nested StructuresA structure can have another structure as a member.

struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short year; double gpa; };

Page 26: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Members of Nested Structures

• Use the dot operator multiple times to dereference fields of nested structures

Student s5;

s5.pData.name = "Joanne";

s5.pData.city = "Tulsa";

Page 27: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example

• Create a structTime that contains data members, hour, minute, second to store the time value, provide a function that sets hour, minute, second to zero, provide three function for converting time to ( 24 hour ) and another one for converting time to ( 12 hour ) and a function that sets the time to a certain value specified by three parameters

Page 28: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Arrays of Structures• Structures can be defined in arrays

• Structures can be used in place of parallel arrays

Student stuList[20];

• Individual structures accessible using subscript notation

• Fields within structures accessible using dot notation:

cout << stuList[5].studentID;

Page 29: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Structures as Function Arguments

• May pass members of struct variables to functions computeGPA(s1.gpa);

• May pass entire struct variables to functions showData(s5);

• Can use reference parameter if function needs to modify contents of structure variable

Page 30: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example

Coffee shop needs a program to computerize its inventory. The data will be Coffee name, price, and amount in stock, sell by year. The function on coffee are: prepare to enter stock, Display coffee data, change price, add stock (add new batch), sell coffee, remove old stock (check sell by year).

Page 31: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Notes on Passing Structures• Using a value parameter for structure can

slow down a program and waste space

• Using a reference parameter speeds up program, but allows the function to modify data in the structure

• To save space and time, while protecting structure data that should not be changed, use a const reference parameter

void showData(const Student &s) // header

Page 32: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Returning a Structure from a Function

• Function can return a structStudent getStuData(); // prototype

s1 = getStuData(); // call

• Function must define a local structure – for internal use – to use with return statement

Page 33: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Returning a Structure Example

Student getStuData() { Student s; // local variable cin >> s.studentID; cin.ignore(); getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; }

Page 34: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example

• Design a struct named BankAccount with data: balance, number of deposits this month, number of withdrawals, annual interest rate, and monthly service charges. The program has functions: Deposit (amount) {add amount to balance and increment number of deposit by one}, Withdraw (amount) {subtract amount from balance and increment number of withdrawals by one}, CalcInterest() { update balance by amount = balance * (annual interest rate /12)}, and MonthlyPocess() {subtract the monthly service charge from balance, set number of deposit, number of withdrawals and monthly service charges to zero}.

Page 35: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Pointers to Structures

• A structure variable has an address

• Pointers to structures are variables that can hold the address of a structure:

Student * stuPtr, stu1;

• Use the & operator to assign an address:

stuPtr = & stu1;

• A structure pointer can be a function parameter

Page 36: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Accessing Structure Members via Pointer Variables

• Use () to dereference the pointer variable, not the field within the structure:

cout << (*stuPtr).studentID;

• You can use the structure pointer operator ( -> ), a.k.a arrow operator to eliminate use of(*).

cout << stuPtr -> studentID;

Page 37: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Pointers to Structures• You may take the address of a structure variable and create

variables that are pointers to structures.

Circle *cirPtr; // cirPtr is a pointer to a CircleCirPtr = &piePlate;

*cirPtr.radius = 10; // incorrect way to access Radius because the dot operator // has higher precedence than the indirection operator

(*cirPtr).radius = 10; //correct access to Radius cirPtr -> radius = 10;

// structure pointer operator ( -> ), easier notation for // dereferencing structure pointers

Page 38: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example

• Write a complete program to– Define a person struct with members: ID, name,

address, and telephone number. The functions are change_data( ), get_data( ), and display_data( ).

– Declare record table with size N and provide the user to fill the table with data.

– Allow the user to enter certain ID for the Main function to display the corresponding person's name, address, and telephone number.

Page 39: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Linked List

Page 40: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Unions

• Similar to a struct, but– all members share a single memory location (which saves space)– only 1 member of the union can be used at a time

• Declared using key word union• Otherwise the same as struct• Variables defined and accessed like struct variables

Page 41: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Example union Declaration

union WageInfo{

double hourlyRate; float annualSalary;};

union tag

Notice the required

;

union members

Page 42: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Anonymous Union

• A union without a tag:union { ... };

• With no tag you cannot create additional union variables of this type later

• Allocates memory at declaration time

• Refer to members directly without dot operator

Page 43: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types

• An enumerated data type is a programmer-defined data type.

It consists of values known as enumerators, which represent integer constants.

Page 44: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types

• Example:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };

• The identifiers MONDAY, TUESDAY, WEDNESDAY, THURSDAY, and FRIDAY, which are listed inside the braces, are enumerators. They represent the values that belong to the Day data type. The enumerators are named constants.

Page 45: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types

• Once you have created an enumerated data type in your program, you can define variables of that type. Example:

Day workDay;

• This statement defines workDay as a variable of the Day type.

Page 46: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types

• We may assign any of the enumerators MONDAY, TUESDAY, WEDNESDAY, THURSDAY, or FRIDAY to a variable of the Day type.

• Example:

workDay = WEDNESDAY;

Page 47: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };

In memory...

MONDAY = 0TUESDAY = 1WEDNESDAY = 2THURSDAY = 3FRIDAY = 4

Page 48: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types• Using the Day declaration, the following

code...

cout << MONDAY << " " << WEDNESDAY << " “ << FRIDAY << endl;

...will produce this output:

0 2 4

Page 49: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Assigning an Enumerator to an int Variable

• You CAN assign an enumerator to an int variable. For example:

int x;x = THURSDAY;

• This code assigns 3 to x.

Page 50: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Enumerated Data Types• Program 11-13 shows enumerators used to

control a loop:

// Get the sales for each day.

for (index = MONDAY; index <= FRIDAY; index++){ cout << "Enter the sales for day " << index << ": "; cin >> sales[index];}

// Would not work if index was an enumerated type

Page 51: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Using an enum Variable to Step through an Array's Elements

• Because enumerators are stored in memory as integers, you can use them as array subscripts.

For example:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };

const int NUM_DAYS = 5;

double sales[NUM_DAYS];

sales[MONDAY] = 1525.00; sales[TUESDAY] = 1896.50; sales[WEDNESDAY] = 1975.63; sales[THURSDAY] = 1678.33; sales[FRIDAY] = 1498.52;

Page 52: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

STRUCT, TYPEDEF, ENUM & UNION You cannot use the typedef specifier inside a

function definition. When declaring a local-scope identifier by the same

name as a typedef, or when declaring a member of a structure or union in the same scope or in an inner scope, the type specifier must be specified.

For example,

typedef float TestType; int main(void) { ...  } // function scope (local)int MyFunct(int){      // same name with typedef, it is OK      int TestType;}

www.tenouk.com, © 57/93

Page 53: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

STRUCT, TYPEDEF, ENUM & UNION Names for structure types are often defined

with typedef to create shorter and simpler type name.

For example, the following statements,

typedef  struct Card MyCard;typedef unsigned short USHORT;

Defines the new type name MyCard as a synonym for type struct Card and USHORT as a synonym for type unsigned short.

Programmers usually use typedef to define a structure (also union, enum and class) type so a structure tag is not required.

For example, the following definition.

typedef struct{      char  *face;      char  *suit;} MyCard; 62/93

Page 54: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Creating Header File and File Re-inclusion Issue

It is a normal practice to separate structure, function, constants, macros, types and similar definitions and declarations in a separate header file(s).

Then, those definitions can be included in main() using the include directive (#include).

It is for reusability and packaging and to be shared between several source files.

Include files are also useful for incorporating declarations of external variables and complex data types.

You need to define and name the types only once in an include file created for that purpose.

The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears.

www.tenouk.com, © 54/93

Page 55: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

The syntax is one of the following,

1. #include "path-spec"2. #include <path-spec>

Both syntax forms cause replacement of that directive by the entire contents of the specified include file.

The difference between the two forms is the order in which the preprocessor searches for header files when the path is incompletely specified.

Preprocessor searches for header files when the path is incompletely specified.

www.tenouk.com, © 42/93

Page 56: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

STRUCT, TYPEDEF, ENUM & UNION

Step: Firstly, add new header file to the existing project.

www.tenouk.com, © 45/93

Page 57: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

STRUCT, TYPEDEF, ENUM & UNION

Step: Put the meaningful header file name.

www.tenouk.com, © 46/93

Page 58: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Abstract Data Types

• A programmer-created data type that specifies– legal values that can be stored– operations that can be done on the values

• The user of an abstract data type does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

Page 59: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Object-Oriented Programming

• Procedural programming focuses on the process/actions that occur in a program

• Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of Abstract Data Types, or ADTs.

Page 60: C++ Structured Data and Classes. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.

Limitations of Procedural Programming

• Use of global data may allow data corruption

• Programs are often based on complex function hierarchies – difficult to understand and maintain– difficult to modify and extend– easy to break


Recommended