Introduction to Object-Oriented Programming
description
Transcript of Introduction to Object-Oriented Programming
Introduction to Object-Oriented Programming
Prof. Shie-Jue Lee
Dept. of Electrical Engineering
National Sun Yat-sen University
Problem
Write a program to maintain an address book. The program should repeatedly ask the user whether to display the names and addresses, to add a name and address, to delete a name and address, or to quit. When the names are displayed, they should be listed in alphabetical order. When the program terminates, the names and addresses should be written to a file. The first time the program is run, the program should create the address book; thereafter, each time the program is run, it should read the file and then present the options to the user.
MAINTAINING AN ADDRESS BOOK ---Problem2
MAINTAINING AN ADDRESS BOOK---Sample Input/Output3
MAINTAINING AN ADDRESS BOOK---Sample Input/Output4
MAINTAINING AN ADDRESS BOOK---Sample Input/Output5
MAINTAINING AN ADDRESS BOOK---Sample Input/Output6
MAINTAINING AN ADDRESS BOOK---Sample Input/Output7
C++ Implementation
#include <iostream>#include <fstream>#include <iomanip>#include <cstdlib>#include <cstring>using namespace std;const int MaxNo = 30; // max numb of names and addressesconst int MaxFld = 81; // max length of one recordconst char filename[ ] = "address.dat";const int RespSize = 30; // max length of user responsevoid show( char list[ ][ MaxFld ], int no );bool add( char name[ ], char list[ ][ MaxFld ], int& no );bool del( int i, char list[ ][ MaxFld ], int& no );void init( char list[ ][ MaxFld ], int& no );void quit( char list[ ][ MaxFld ], int no );
MAINTAINING AN ADDRESS BOOK---C++ Implementation8
int main() { char addr[ MaxNo ][ MaxFld ]; char name[ MaxFld ]; char resp[ RespSize ]; int number; int index; // read in names from a file if it exists // and set number to the number of records init( addr, number ); do { cout << "\n\n[S]how names and addresses\n" << "[A]dd a name and address\n" << "[D]elete a name and address\n" << "[Q]uit\n" << "Your choice? "; cin.getline( resp, RespSize );
MAINTAINING AN ADDRESS BOOK---C++ Implementation9
switch ( resp[ 0 ] ) { case 'S': case 's': show( addr, number ); break; case 'A': case 'a': cout << "Name and address to add\n"; cin.getline( name, MaxFld ); if ( !add( name, addr, number ) ) cout << "\a*** Out of room, unable to add: " << name << endl; break;
MAINTAINING AN ADDRESS BOOK---C++ Implementation10
MAINTAINING AN ADDRESS BOOK
case 'D': case 'd': cout << "Number of name to delete? "; cin.getline( resp, RespSize ); index = atoi( resp ); if ( !del( index, addr, number ) ) cout << "\a*** Unable to delete number: " << index << endl; break;case 'Q': case 'q': quit( addr, number ); break; default: cout << "\a*** Illegal choice; try again\n"; break; } } while ( resp[ 0 ] != 'Q' && resp[ 0 ] != 'q' ); return 0;}
11
MAINTAINING AN ADDRESS BOOK
// show prints the records and numbers them starting with zero. The
// numbers are printed in a field of width 3, which is why setw( 3 )
// is used.// show also prints PerScreen (20) records per screen.void show( char list[ ][ MaxFld ], int no ) { int i; char resp[ RespSize ]; const int PerScreen = 20; for ( i = 0; i < no; i++ ) { cout << setw( 3 ) << i << ' ' << list[ i ] << endl; if ( ( i + 1 ) % PerScreen == 0 ) { cout << "Hit RETURN to continue: "; cin.getline( resp, RespSize ); } }}
12
MAINTAINING AN ADDRESS BOOK
// add adds a record if possible and updates the number of records
bool add( char name[ ], char list[ ][ MaxFld ], int& no ) {
int i; // out of room? if ( no >= MaxNo ) return false; // find correct position for name for ( i = no - 1; i >= 0 && strcmp( name, list[ i ] ) < 0; i-- ) strcpy( list[ i + 1 ], list[ i ] ); strcpy( list[ i + 1 ], name ); no++; return true;}
13
// del deletes the record at index I and updates the number of
// recordsbool del( int i, char list[ ][ MaxFld ], int& no ) { int j; // is i in bounds? if ( i < 0 || i >= no ) return false; // move names down to delete entry i for ( j = i; j < no - 1; j++ ) strcpy( list[ j ], list[ j + 1 ] ); no--; return true;}
MAINTAINING AN ADDRESS BOOK---C++ Implementation14
// init reads names from the file address.dat and sets no to the
// number of records read. If address.dat does not exist, init
// simply sets no to zero and returns.void init( char list[ ][ MaxFld ], int& no ) { ifstream in; in.open( filename ); no = 0; // check if file exists; if not, return. if ( !in ) return; // read records until out of room or end-of-file while ( no < MaxNo ) { in.getline( list[ no ], MaxFld ); if ( !strlen( list[ no ] ) ) break; no++; } in.close();}
MAINTAINING AN ADDRESS BOOK---C++ Implementation15
// quit writes the records to address.datvoid quit( char list[ ][ MaxFld ], int no ) { ofstream out; out.open( filename ); int i; // write records to address.dat for ( i = 0; i < no; i++ ) out << list[ i ] << endl; out.close();}
MAINTAINING AN ADDRESS BOOK---C++ Implementation16
A TIME STAMP CLASS ---Problem
17
A TIME STAMP CLASS ---Problem
18
A TIME STAMP CLASS ---Sample Output
19
A TIME STAMP CLASS ---Sample Output
20
A TIME STAMP CLASS ---Sample Output
21
C++ Implementation
A TIME STAMP CLASS ---C++
Implementation22
23
A TIME STAMP CLASS ---C++
Implementation
24
A TIME STAMP CLASS ---C++
Implementation
#include <iostream>#include <ctime> #include <cstring>using namespace std;class TimeStamp {public: void set( long s = 0 ); time_t get(); const char* getAsString(); const char* getYear(); const char* getMonth(); const char* getDay(); const char* getHour(); const char* getMinute(); const char* getSecond();
25
A TIME STAMP CLASS ---C++
Implementation
private: const char* extract( int, int ); time_t stamp; char string[ 30 ]; // holds ctime's return string};void TimeStamp::set( long s ) { if ( s <= 0 ) stamp = time( 0 ); else stamp = s; }time_t TimeStamp::get() { return stamp; }const char* TimeStamp::getAsString() { return ctime( &stamp );}
26
A TIME STAMP CLASS ---C++
Implementation
const char* TimeStamp::extract( int offset, int count ) { char temp[ 30 ]; strcpy( temp, ctime( &stamp ) ); strncpy( string, temp + offset, count ); string[ count ] = '\0'; // ensure a string return string;}const char* TimeStamp::getYear() { return extract( 20, 4 );}const char* TimeStamp::getMonth() { return extract( 4, 3 );}
27
A TIME STAMP CLASS ---C++
Implementation
const char* TimeStamp::getDay() { return extract( 0, 3 );}const char* TimeStamp::getHour() { return extract( 11, 2 );}const char* TimeStamp::getMinute() { return extract( 14, 2 );}const char* TimeStamp::getSecond() { return extract( 17, 2 );}
28
A TIME STAMP CLASS ---C++
Implementation
ProblemDevelop an inheritance hierarchy to handle sequences of strings and sorted sequences of strings. A sequence is a list in which there is a first element, a second element, and so on.
For example, in the sequence
Abby George Ben
Abby is the first member, George is the second member, and Ben is the third member. This sequence is considered distinct from the sequence
George Ben Abby
29
A SEQUENCE HIERARCHY ---Problem
because, for example, the first member, George, is different from the first member, Abby, of the first sequence.
A sorted sequence is a sequence in which the elements are in sorted(ascending)order.
For example, the sequence
Abby Ben George
Is a sorted sequence because the elements are in sorted order. The sequence
Abby George Ben
Is not a sorted sequence because Ben should precede George in sorted order.
30
A SEQUENCE HIERARCHY ---Problem
Class Sequence has data members To hold strings. To hold a file name. To hold the index of the last string. To handle input and output files.
These members are protected so that they are visible throughout the class hierarchy.
Class Sequence has public methods to Add a string at a designated position. Delete a string at a designated position. To output the sequence.
31
A SEQUENCE HIERARCHY ---Problem
Class Sequence also has a default constructor, a one-parameter char [ ] constructor, and a destructor.
The default constructor Sets the index of the last string to -1 to indicate that
no strings are in the sequence. Sets the file name to the null string to indicate that no
file name has been given.
32
A SEQUENCE HIERARCHY ---Problem
The one-parameter char [ ] constructor Sets the index of the last string to -1 to indicate that
no strings are in the sequence. Copies the file name passed into the data member
that holds a file name. Attempts to open the file for input. If the file cannot be
opened, the constructor simply returns. Reads the sequence from the file until end-of-file or
until storage is exhausted, whichever occurs first. Closes the file.
33
A SEQUENCE HIERARCHY ---Problem
The destructor Returns if the file name is the null string. Open the file for output. Writes the sequence to the file. Closes the file.
34
A SEQUENCE HIERARCHY ---Problem
35
A SEQUENCE HIERARCHY ---Sample
Input/Output
36
A SEQUENCE HIERARCHY ---Sample
Input/Output
37
A SEQUENCE HIERARCHY ---C++
Implementation
38
A SEQUENCE HIERARCHY ---C++
Implementation
39
A SEQUENCE HIERARCHY ---C++
Implementation
40
A SEQUENCE HIERARCHY ---C++
Implementation#include <iostream>#include <fstream>#include <cstdlib>#include <cstring>using namespace std;const int MaxStr = 50;const int MaxSize = 80;class Sequence {public: bool addS( int, char [ ] ); bool del( int ); void output(); Sequence(); Sequence( char [ ] ); ~Sequence();
41
A SEQUENCE HIERARCHY ---C++
Implementation
protected: char s[ MaxStr ][ MaxSize ]; char filename[ MaxSize ]; int last; ifstream in; ofstream out;};
42
A SEQUENCE HIERARCHY ---C++
Implementation
bool Sequence::addS( int pos, char entry[ ] ) {
if ( last == MaxStr - 1 || pos < 0 || pos > last + 1 ) return false; for ( int i = last; i >= pos; i-- ) strcpy( s[ i + 1 ], s[ i ] ); strcpy( s[ pos ], entry ); last++; return true;}
43
A SEQUENCE HIERARCHY ---C++
Implementation
bool Sequence::del( int pos ) { if ( pos < 0 || pos > last ) return false;
for ( int i = pos; i < last; i++ ) strcpy( s[ i ], s[ i + 1 ] ); last--; return true;}
void Sequence::output() { for ( int i = 0; i <= last; i++ ) cout << i << " " << s[ i ] << endl;}
44
A SEQUENCE HIERARCHY ---C++
ImplementationSequence::Sequence() { last = -1; filename[ 0 ] = '\0'; }
Sequence::Sequence( char fname[ ] ) { last = -1; strcpy( filename, fname ); in.open( filename ); if ( !in ) return; while ( last < MaxStr - 1 ) { in.getline( s[ last + 1 ], MaxSize ); if ( !strlen( s[ last + 1 ] ) ) break; last++; } in.close(); }
45
A SEQUENCE HIERARCHY ---C++
ImplementationSequence::~Sequence() { if ( filename[ 0 ] == '\0' ) return; out.open( filename ); for ( int i = 0; i <= last; i++ ) out << s[ i ] << endl; out.close();}class SortedSeq : public Sequence {public: bool addSS( char [ ] ); SortedSeq(); SortedSeq( char [ ] );protected: void sort();};
46
A SEQUENCE HIERARCHY ---C++
Implementation
void SortedSeq::sort() { char temp[ MaxSize ]; int j; for ( int i = 0; i <= last - 1; i++ ) { strcpy( temp, s[ i + 1 ] ); for ( j = i; j >= 0; j-- ) if ( strcmp( temp, s[ j ] ) < 0 ) strcpy( s[ j + 1 ], s[ j ] ); else break; strcpy( s[ j + 1 ], temp ); }}
47
A SEQUENCE HIERARCHY ---C++
Implementation
bool SortedSeq::addSS( char entry[ ] ) { int i; for ( i = 0; i <= last; i++ ) if ( strcmp( entry, s[ i ] ) <= 0 ) break; return addS( i, entry );}
SortedSeq::SortedSeq() : Sequence() { }
SortedSeq::SortedSeq( char fname[ ] ) : Sequence( fname ) {
sort();}
A COMPLEX NUMBER CLASS
---Problem48
A COMPLEX NUMBER CLASS
---Problem49
A COMPLEX NUMBER CLASS ---
Sample Output50
A COMPLEX NUMBER CLASS ---C++
Implementation51
A COMPLEX NUMBER CLASS ---C++
Implementation52
A COMPLEX NUMBER CLASS ---C++
Implementation53class Complex {public: Complex(); // default Complex( double ); // real given Complex( double, double ); // both given void write() const; // operator methods Complex operator+( const Complex& ) const; Complex operator-( const Complex& ) const; Complex operator*( const Complex& ) const; Complex operator/( const Complex& ) const;private: double real; double imag;};
A COMPLEX NUMBER CLASS ---C++
Implementation54
// default constructorComplex::Complex() { real = imag = 0.0;}// constructor -- real given but not imagComplex::Complex( double re ) { real = re; imag = 0.0;}// constructor -- real and imag givenComplex::Complex( double re, double im ) { real = re; imag = im;}
A COMPLEX NUMBER CLASS ---C++
Implementation55
void Complex::write() const { cout << real << " + " << imag << 'i';}// Complex + as binary operatorComplex Complex::operator+( const Complex& u ) const {
Complex v( real + u.real, imag + u.imag ); return v;}// Complex - as binary operatorComplex Complex::operator-( const Complex& u ) const {
Complex v( real - u.real, imag - u.imag ); return v;}
A COMPLEX NUMBER CLASS ---C++
Implementation56
// Complex * as binary operatorComplex Complex::operator*( const Complex& u ) const {
Complex v( real * u.real - imag * u.imag, imag * u.real + real * u.imag ); return v;}// Complex / as binary operatorComplex Complex::operator/( const Complex& u ) const {
double abs_sq = u.real * u.real + u.imag * u.imag; Complex v( ( real * u.real + imag * u.imag ) / abs_sq,
( imag * u.real - real * u.imag ) / abs_sq );
return v;}