practice building classes

24
Practice Building Practice Building Classes Classes Modeling Objects Modeling Objects

Upload: charo

Post on 13-Jan-2016

19 views

Category:

Documents


0 download

DESCRIPTION

Practice Building Classes. Modeling Objects. Problem. Write a program that computes the Dean’s List (full-time students whose GPA ³ 3.0), using a student data file. Each student-record in the file consists of four lines: 12345 Jane Doe 3.35 14 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Practice Building Classes

Practice Building ClassesPractice Building Classes

Modeling ObjectsModeling Objects

Page 2: Practice Building Classes

ProblemProblem

Write a program that computes the Dean’s List Write a program that computes the Dean’s List (full-time students whose GPA (full-time students whose GPA 3.0), using a 3.0), using a student data file.student data file.

Each student-record in the file consists of four Each student-record in the file consists of four lines:lines:

12345 12345 Jane Doe Jane Doe 3.35 143.35 14

representing student representing student Jane DoeJane Doe, with student id , with student id 1234512345, with GPA , with GPA 3.353.35 and and 1414 credit hrs this credit hrs this semester.semester.

Page 3: Practice Building Classes

BehaviorBehavior

Our program should prompt for and read the Our program should prompt for and read the name of the data file from the user. It name of the data file from the user. It should then open an ifstream to that file. It should then open an ifstream to that file. It should then prompt for and read the name of should then prompt for and read the name of an output file and open an ofstream to that an output file and open an ofstream to that file. Using an input loop, our program should file. Using an input loop, our program should read in the sequence of students. It should read in the sequence of students. It should then process this sequence by printing to the then process this sequence by printing to the ofstream each full-time student whose GPA ofstream each full-time student whose GPA is 3.0 or greater.is 3.0 or greater.

Page 4: Practice Building Classes

ObjectsObjects

Description Type Kind NameDescription Type Kind Namein-file name string varying inFileName

input fstream ifstream varying fin

students vector<Student> varying students

GPA double varying students[i].GPA()

out-file name string varying outFileName

output fstream ofstream varying fout

Page 5: Practice Building Classes

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Name

display a string yes string <<

read a string yes string >>

open/close fstreams yes fstream --

read students in an ?? -- for, if input loop break

identify Deans List ?? -- for, if students [], ??

output a student ?? -- ??

Page 6: Practice Building Classes

AlgorithmAlgorithm0. Display purpose of program0. Display purpose of program1. Prompt for and read name of input file from 1. Prompt for and read name of input file from cincin into into

inFileNameinFileName..2. Open 2. Open finfin to to inFileNameinFileName, , foutfout to to outFileNameoutFileName, verify , verify

opens.opens.3. Read sequence of students from 3. Read sequence of students from finfin into into studentsstudents, ,

using an input loop. using an input loop.4. Close 4. Close finfin..5. Prompt for and read name of output file from 5. Prompt for and read name of output file from cincin into into

outFileNameoutFileName..6. Write 6. Write studentsstudents qualifying for the Dean’s List to qualifying for the Dean’s List to foutfout..7. Close 7. Close foutfout..8. Display a ‘processing completed’ message via 8. Display a ‘processing completed’ message via coutcout..

Page 7: Practice Building Classes

OCD with ClassesOCD with Classes

0. Specify the behavior of the program.0. Specify the behavior of the program.1. Identify the objects in the behavior.1. Identify the objects in the behavior.

1a. If an object cannot be modeled with available types,declare a class by which such objects can be

modeled.2. Identify the operations in the behavior.2. Identify the operations in the behavior.

2a. If an operation is not predefined,2a. If an operation is not predefined,build a function to perform that operation.build a function to perform that operation.

2b. If the left operand of an operation is a class object,make the operation a function member of the class.

3. Organize your objects and operations into an algorithm.3. Organize your objects and operations into an algorithm.

Page 8: Practice Building Classes

A Student ClassA Student Class

Begin by defining variables to store the attributes of the Begin by defining variables to store the attributes of the object being represented (a student) in a class header file object being represented (a student) in a class header file (e.g., Student.h):(e.g., Student.h):

int myID;string myName;double myGPA;int myCredits;

Clearly, it would be easy to add other data members Clearly, it would be easy to add other data members (academic year, address, ...) as necessary.(academic year, address, ...) as necessary.

Page 9: Practice Building Classes

Building ClassesBuilding Classes

We then wrap these variables in a class We then wrap these variables in a class declaration:declaration:class Student{ public: private: int myID; string myName; double myGPA; int myCredits;};

Page 10: Practice Building Classes

PrototypesPrototypesclass Student{ public:

private: // ... data members omitted};

Student(); Student(int id, const string & Name, double gpa, int credits); int ID() const; string Name() const; double GPA() const; int Credits() const; friend istream & operator>>(istream & in,

Student & stu); friend ostream & operator<<(ostream & in,

const Student & stu);

Page 11: Practice Building Classes

Operation: Operation: Default ConstructorDefault Constructor

The default constructor initializes the data The default constructor initializes the data members to default values:members to default values:

Student aStudent;

Specification:Specification:Postcondition: myid == 0 && myName == “” &&Postcondition: myid == 0 && myName == “” && myGPA == 0.0 && myCredits == 0.myGPA == 0.0 && myCredits == 0.

Page 12: Practice Building Classes

Default ConstructorDefault Constructor

inline Student::Student(){ myID = 0; myName = “”; myGPA = 0.0; myCredits = 0;}

This is sufficiently simple to define This is sufficiently simple to define inlineinline in Student.h: in Student.h:

Page 13: Practice Building Classes

Operation:Operation:Explicit-Value ConstructorExplicit-Value Constructor

Student aStudent(12345, “Jane Doe”, 3.35, 14);

This constructor lets you initialize the data This constructor lets you initialize the data members to specified values:members to specified values:

Specification:Specification:Receive: Receive: idid, an int; , an int; namename, a string; , a string; gpagpa, a double, and , a double, and creditscredits, an int., an int.Precondition: id is a valid id, Precondition: id is a valid id, gpagpa is a valid gpa, and is a valid gpa, and creditscredits is a valid number of credits. is a valid number of credits.Postcondition: Postcondition: myidmyid == == idid && && myNamemyName == == namename && && myGPAmyGPA == == gpagpa && && myCreditsmyCredits == == creditscredits..

Page 14: Practice Building Classes

Explicit-Value ConstructorExplicit-Value Constructor

// ...#include “Student.h”

Student::Student(int id, const string & name, double gpa, int credits){ assert(id > 0 && gpa >= 0.0 && gpa <= 4.0 && credits > 0 && credits < 21); myID = id; myName = name; myGPA = gpa; myCredits = credits;}

This is sufficiently complicated to define in Student.cpp:This is sufficiently complicated to define in Student.cpp:

Page 15: Practice Building Classes

Operation: Operation: ExtractorsExtractors

The extractors retrieve data member The extractors retrieve data member values:values:

cout << aStudent.ID() << aStudent.Name() << aStudent.GPA() << aStudent.Credits();

Specifications:Specifications: ID:ID: Return Return myIDmyID..

Name:Name: Return Return myNamemyName..GPA:GPA: Return Return myGPAmyGPA..Credits:Credits: Return Return myCreditsmyCredits..

Page 16: Practice Building Classes

Default ConstructorDefault Constructor

inline int Student::ID() const{ return myID;}

These are sufficiently simple to define These are sufficiently simple to define inlineinline in Student.h: in Student.h:

inline string Student::Name() const{ return myName;}

inline string Student::GPA() const{ return myGPA;}

inline string Student::Credits() const{ return myCredits;}

Page 17: Practice Building Classes

Operation:Operation:InputInput

cin >> aStudent;

The input operator lets you read Student The input operator lets you read Student values:values:

Specification:Specification:Receive: Receive: inin, an istream; , an istream; stustu, a Student., a Student.Precondition: in contains a valid Student value.Precondition: in contains a valid Student value.Input: the Student value from Input: the Student value from inin..Passback: Passback: inin, the Student value extracted from it;, the Student value extracted from it; stustu, containing the extracted value., containing the extracted value.Return: Return: inin, for chaining., for chaining.

Page 18: Practice Building Classes

Input OperatorInput Operator

// ...istream & operator>>(istream & in, Student & stu){ in >> stu.myID; // read id on one line char ch; in.get(ch); // eat the newline getline(in, stu.myName); // read name (2 words) in >> stu.myGPA // read GPA >> stu.myCredits; // read credits assert(in.good()); // weak precondition check return in; // allow chaining}

This is sufficiently complicated to define in Student.cpp.This is sufficiently complicated to define in Student.cpp.

Its form is dictated by the record-format in the data file:Its form is dictated by the record-format in the data file:

Page 19: Practice Building Classes

Operation:Operation:OutputOutput

cout << aStudent << endl;

The output operator lets you write Student The output operator lets you write Student values:values:

Specification:Specification:Receive: Receive: outout, an ostream; , an ostream; stustu, a Student., a Student.Output: Output: stustu’s Student value, via ’s Student value, via outout..Passback: Passback: outout, with the Student value inserted into , with the Student value inserted into

it.it.Return: Return: outout, for chaining., for chaining.

Page 20: Practice Building Classes

Output OperatorOutput Operator

// ...ostream & operator<<(ostream & out, const Student & stu){ out << stu.myID << ‘\n’ // put id on one line << stu.myName << ‘\n’ // put name << stu.myGPA << ‘ ‘ // put GPA << stu.myCredits; // put credits return out; // allow chaining}

This is sufficiently complicated to define in Student.cpp.This is sufficiently complicated to define in Student.cpp.

We will use a format consistent with that in the data file:We will use a format consistent with that in the data file:

Page 21: Practice Building Classes

Coding Our AlgorithmCoding Our AlgorithmWe are now ready to implement our We are now ready to implement our

algorithm...algorithm...// deansList.cpp// ... documentation// ... other #includes#include “Student.h”

int main(){ cout << “\nTo generate the Dean’s List,” << “\n enter the input file name: “; string inFileName; cin >> inFileName;

ifstream fin(inFileName.data()); assert(fin.is_open());

Page 22: Practice Building Classes

Coding (Coding (Ct’dCt’d))// ... deansList.cpp continued

Student aStudent; vector<Student> students; for (;;) { fin >> aStudent; if (fin.eof()) break; students.push_back(aStudent); }

fin.close();

// ...

Page 23: Practice Building Classes

Coding (Coding (Ct’dCt’d))// ... deansList.cpp continued

cout << “\nEnter the output file name: “; string outFileName; cin >> outFileName;

ofstream fout(outFileName.data()); assert(fout.is_open());

for (unsigned i = 0; i < students.size(); i++) if (students[i].GPA() >= 3.0 && students[i].Credits() >= 12) fout << students[i] << “\n\n”;

fout.close(); cout << “\nProcessing complete. Results are in “ << outFileName << endl;}

Page 24: Practice Building Classes

SummarySummaryC++ C++ classesclasses allow “real world” objects to be modeled in software. allow “real world” objects to be modeled in software.

Classes are objects, and can be stored in containers, such as the STL Classes are objects, and can be stored in containers, such as the STL vector.vector.

Most classes require at least:Most classes require at least:– a default-value constructora default-value constructor

– an explicit-value constructoran explicit-value constructor

– extractor functionsextractor functions

– I/O functionsI/O functions