C O D
E S A M P L E S
Feel
free to widen this frame so you see all the code that's supposed to be on each
line
Bookmarks |
// Name: Convenience
store owner
// Version: 1.0
// Purpose: Convert the price of an
item in U.S. pennies per pound to
//
Canadian dollars per kilogram.
#include <iostream.h>
//------------------------ calculator
object ---------------------------------
void main()
{
double theOutput; // Answer displayed to the user
double dollarsPerKg; // Item's cost in Canadian dollars per
kilogram
int theInput; // Input entered by the user
int penniesPerLb; // Price in U.S. pennies per pound of an
item
//-------------------- input object
---------------------------------------
//
Get the input.
cin >> theInput;
//------------------- end of input
object --------------------------------
penniesPerLb = theInput;
//-------------------- computing object
-----------------------------------
const double kgPerLb = .4536; // Number of kilograms in a pound
const double dollarsCanPerUS = 1.26; //
Number of Canadian dollars per
// U.S. dollar (exchange rate)
const int penniesPerDollar = 100; // Number of pennies per U.S. dollar
dollarsPerKg = penniesPerLb/kgPerLb * dollarsCanPerUS/penniesPerDollar;
//-------------------- end of computing
object ---------------------------
theOutput = dollarsPerKg;
//-------------------- output object
--------------------------------------
// Display the answer.
cout << theOutput << endl;
//------------------- end of output
object --------------------------------
}
//---------------------- end of
calculator object ----------------------------
//*******************************************************************************
#include <iostream.h>
//------------------------ teller object -------------------------------------
void main()
{
int countOfTwenties; // Count of $20Us to be returned
int countOfTens; // Count of $10Us to be returned
int countOfFives; // Count of $5Us to be returned
int countOfOnes; // Count of $1Us to be returned
int countOfQuarters; // Count of quarters to be returned
int countOfDimes; // Count of dimes to be returned
int countOfNickels; // Count of nickels to be returned
int countOfPennies; // Count of pennies to be returned
int theAmount; // Amount to be changed
//-------------------- input object
---------------------------------------
// Get the amount from the user.
cin >> theAmount;
//----------------- end of input object
-----------------------------------
//-------------------- computing object
-----------------------------------
//-------------------- cash drawer
object ---------------------------------
const int twentyValue = 2000; // Number of pennies in $20
const int tenValue = 1000; // Number of pennies in $10
const int fiveValue = 500; // Number of pennies in $5
const int oneValue = 100; // Number of pennies in $1
const int quarterValue = 25; // Number of pennies in a quarter
const int dimeValue = 10; // Number of pennies in a dime
const int nickelValue = 5; // Number of pennies in a nickel
const int pennyValue = 1; // Number of pennies in a penny
const char twentyName[] =
"twenties"; // Label for
$20 bills
const char tenName[] =
"tens"; // Label for
$10 bills
const char fiveName[] =
"fives"; //_Label for
$5 bills
const char oneName[] =
"ones"; // Label for
$1 bills
const char quarterName[] = "quarters"; // Label for quarter coins
consT char dimeName[] =
"dimes"; // Label for
dime coins
const char nickelName[] =
"nickels"; // Label for
nickel coins
const char pennyName[] =
"pennies"; // Label for
penny coins
//----------------- end of cash drawer
object -----------------------------
// Determine the amount of each
denomination to be returned.
countOfTwenties = theAmount /
twentyValue;
theAmount = theAmount % twentyValue;
countOfTens = theAmount / tenValue;
theAmount = theAmount % tenValue;
countOfFives = theAmount / fiveValue;
theAmount = theAmount % fiveValue;
countOfOnes = theAmount / oneValue;
theAmount = theAmount % oneValue;
countOfQuarters = theAmount /
quarterValue;
theAmount = theAmount % quarterValue;
countOfDimes = theAmount / dimeValue;
theAmount = theAmount % dimeValue;
countOfNickels = theAmount /
nickelValue;
theAmount = theAmount % nickelValue;
countOfPennies = theAmount /
pennyValue;
theAmount = theAmount % pennyValue;
//----------------- end of computing
object -------------------------------
//-------------------- output object
--------------------------------------
// Display the results.
cout << countOfTwenties <<
" " << twentyName << endl;
cout << countOfTens <<
" " << tenName << endl;
cout << countOfFives <<
" " << fiveName << endl;
cout << countOfOnes <<
" " << oneName << endl;
cout << countOfQuarters <<
" " << quarterName << endl;
cout << countOfDimes <<
" " << dimeName << endl;
cout << countOfNickels <<
" " << nickelName << endl;
cout << countOfPennies <<
" " << pennyName << endl;
//----------------- end of output
object ----------------------------------
}
//---------------------- end of teller
object --------------------------------
//*******************************************************************************
// Name: The changemaker
// Version: 2.0
// Purpose: Determine the count of each
denomination from twenty dollar bills
//
down through pennies that constitute a given monetary amount.
#include <iostream.h>
//-------------------------------
interfaces ---------------------------------
void inputInt(int& aNumber, const
char prompt[]);
// Arguments:
//
aNumber - out - Integer entered by the user
//
prompt - Message displayed to the user
// Side effect: Prompts for and reads
aNumber.
void outputLine(int aNumber, const char
aString[]);
// Arguments:
//
aNumber - Integer to be displayed
//
aString - Message displayed to identify the output
// Side effect: Display a number and
message followed by a newline.
void divMod(int numerator, int
denominator, int& quotient, int& remainder);
// Arguments:
//
numerator, denominator - two integers
//
ASSUME: numerator >= 0; denominator > 0
//
quotient - out - The quotient of numerator/denominator
//
remainder - out - The remainder of numerator/denominator
// Side effect: Find the result of
integer division of numerator/denominator.
int countForDenom1(int&
amountLeft);
int countForDenom2(int&
amountLeft);
int countForDenom3(int&
amountLeft);
int countForDenom4(int&
amountLeft);
int countForDenom5(int&
amountLeft);
int countForDenom6(int&
amountLeft);
int countForDenom7(int&
amountLeft);
int countForDenom8(int&
amountLeft);
// int countForDenomN(int&
amountLeft)
//
Argument:
//
amountLeft - in - Amount from which to give out the Nth denomination
// ASSUME: amountLeft >= 0.
// - out - Remainder of the amount after giving out the
// the Nth denomination
//
Returns: The count of the Nth denomination in theAmount
//
(Side effect: Reduce amountLeft by the amount of the Nth denomination)
//--------------------------- end of
interfaces ------------------------------
//------------------- cash drawer
object implementation
---------------------
const int denomValue1 = 2000; // Number of pennies in $20.00
const char denomName1[] =
"twenties"; // Name of
$20.00 denomination
const int denomValue2 = 1000; // Number of pennies in $10.00
const char denomName2[] =
"tens"; // Name of
$10.00 denomination
const int denomValue3 = 500; // Number of pennies in $5.00
const char denomName3[] =
"fives"; // Name of $5.00
denomination
const int denomValue4 = 100; // Number of pennies in $1.00
const char denomName4[] =
"ones"; // Name of $1.00
denomination
const int denomValue5 = 25; // Number of pennies in $.25
const char denomName5[] =
"quarters"; // Name of $.25
denomination
const int denomValue6 = 10; // Number of pennies in $.10
const char denomName6[] =
"dimes"; // Name of $.10
denomination
const int denomValue7 = 5; // Number of pennies in $.05
const char denomName7[] =
"nickels"; // Name of $.05
denomination
const int denomValue8 = 1; // Number of pennies in $.01
const char denomName8[] =
"pennies"; // Name of $.01
denomination
//--------------- end of cash drawer object implementation -----------------
//-------------------- teller object
implementation --------------------------
void main( )
{
cout << "Change Maker (version 2)\n\n";
int amountLeftToChange;
// Amount left to be changed
inputInt(amountLeftToChange, "Enter amount to be changed in
pennies: ");
outputLine(countForDenom1(amountLeftToChange), denomName1);
outputLine(countForDenom2(amountLeftToChange), denomName2);
outputLine(countForDenom3(amountLeftToChange), denomName3);
outputLine(countForDenom4(amountLeftToChange), denomName4);
outputLine(countForDenom5(amountLeftToChange), denomName5);
outputLine(countForDenom6(amountLeftToChange), denomName6);
outputLine(countForDenom7(amountLeftToChange), denomName7);
outputLine(countForDenom8(amountLeftToChange), denomName8);
}
//----------------- end of teller
object implementation ----------------------
//---------------------- input object
implementation -------------------------
void inputInt(int& aNumber, const
char prompt[])
{
cout << prompt;
cin >> aNumber;
}
//------------------- end of input
object implementation ---------------------
//--------------------- output object
implementation -------------------------
void outputLine(int aNumber, const char
aString[])
{
cout << aNumber << " " << aString <<
endl;
}
//------------------ end of output
object implementation ---------------------
//-------------------- computing object
implementation -----------------------
void divMod(int numerator, int
denominator, int& quotient, int& remainder)
{
quotient = numerator / denominator;
remainder = numerator % denominator;
}
int countForDenom1(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue1, result,amountLeft);
return result;
}
int countForDenom2(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue2, result,amountLeft);
return result;
}
int countForDeNom3(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue3, result,amountLeft);
return result;
}
int countForDenom4(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue4, result,amountLeft);
return result;
}
int countForDenom5(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue5, result,amountLeft);
return result;
}
int countForDenom6(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue6, result,amountLeft);
return result;
}
int countForDenom7(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue7, result,amountLeft);
return result;
}
int countForDenom8(int& amountLeft)
{
int result; // Value to be
returned
divMod(amountLeft,denomValue8, result,amountLeft);
return result;
}
//----------------- end of computing
object implementation -------------------
//*******************************************************************************
//FILE: date.H
// A simple date class.
class Date {
public:
Date(int d = 31, int m = 12, int y = 2000); // Constructs a date with
//
default values 31 (day), 12 (month), and
//
2000 (year).
//
ASSUME: m/d/y is a valid date.
int theDay() const; // Day
of this date.
int theMonth() const; //
Month of this date.
int theYear() const; //
Year of this date.
void advance(); //
Advances this date to the following day.
private:
int day_;
int month_;
int year_;
};
#include "date.H"
Date :: Date(int d, int m, int y) :
day_(d), month_(m), year_(y)
{ }
int Date :: theDay() const
{
return day_;
}
int Date :: theMonth() const
{
return month_;
}
int Date :: theYear() const
{
return year_;
}
void Date :: advance()
{
day_ += 1;
// advance the day
switch (month_) {
case 1: case 3: case 5: case 7: case 8: case 10:
// January, March, May, July, August, October
if (day_ == 32) {
day_ = 1;
month_ += 1;
} break;
case 12:
// December
if (day_ == 32) {
day_ = 1;
month_ = 1;
year_ += 1;
} break;
case 4: case 6: case 9: case 11:
// April, June, September, November
if (day_ == 31) {
day_ = 1;
month_ += 1;
} break;
case 2:
// February
if (day_ > 29 || day_ == 29 && ( year_ % 4 >
0 || year_ % 100 == 0)
&& year_ % 400 >
0 ) {
day_ = 1;
month_ = 3;
} break;
}
}
//*******************************************************************************
// FILE: simple.h
class SimpleList {
public:
// Constructor
SimpleList();
// Constructs an empty list.
// These methods change the list
void clear();
// Makes the list empty.
void add(int newItem);
// Adds newItem to the list.
// ASSUME: The list is not full.
// These methods tell information about the list
bool member(int anItem) const;
// True if anItem is a list member.
int maximumCapacity() const;
// Maximum possible list size.
int currentSize() const;
// Number of items currently in the list.
private:
// List data
enum {maxSize_ = 100};
// Maximum size of the list
int item_[maxSize_];
// List items
int size_;
// Number of items currently in the list
};
//FILE: SIMPLE.C
#include "simple.H"
SimpleList :: SimpleList() : size_(0)
{ }
void SimpleList :: clear()
{
size_ = 0;
}
void SimpleList :: add(int newItem)
{
item_[size_] = newItem;
size_++;
}
bool SimpleList :: member(int anItem)
const
{
for (int i = 0; i < size_; i++)
if (item_[i] == anItem)
return true;
return false;
}
int SimpleList :: maximumCaPacity()
const
{
return maxSize_;
}
int SimpleList :: currentSize() const
{
return size_;
}
//*******************************************************************************
//FILE: NAMES.H
// Type for representing a person's
name with 49 characters or less.
class Name {
public:
Name(const char n[] = ""); // Creates a name from n, using at most
// the first 50
characters from n, up to
// and including the terminating '\0'.
void copyToString(char target[]); // Copies the characters of the name
to
// target.
// ASSUME: target array >= 50
elements.
void print() const;
// Prints the name to cout.
private:
enum { maxName_ = 50 };
char name_[maxName_];
};
//FILE: CKACCT.H
#include "names.H"
// A simple checking account class
class CheckingAccount {
public:
CheckingAccount(const char n[] = "", float b = 0);
// Creates a checking account with
an owner
// named n and beginning balance b.
// ASSUME: length of n < 50; b
>= 0.
float theBalance() const; //
The account balance
Name theOwner() const; //
Name of the account owner
void deposit(float amt); //
Credits the balance with amt.
// ASSUME: amt >= 0.
void writeCheck(float amt); //
If the current balance is >= amt, amt is
// debited from the balance, else nothing
// nothing is changed.
// ASSUME: amt >= 0.
private:
float balance_;
Name owner_;
};
//FILE: CKACCT.C
#include "ckAcct.H"
CheckingAccount ::
CheckingAccount(const char n[], float b) :
balance_(b), owner_(n)
{ }
Name CheckingAccount :: theOwner()
const
{
return owner_;
}
float CheckingAccount :: theBalance()
const
{
return balance_;
}
void CheckingAccount :: deposit(float
amt)
{
balance_ += amt;
}
void CheckingAccount ::
writeCheck(float amt)
{
if (balance_ >= amt)
balance_ -= amt;
}
//*******************************************************************************
//FILE: RATIONAL.H
// First class rational number tOpe.
class Rational {
public:
Rational(int n = 0, int d = 1);
// Constructs the Rational number n/d
// (d != 0)
// Arithmetic operators.
Rational operator-() const; //
unary -
friend Rational operator+ (const Rational& r, const Rational&
s);
friend Rational operator- (const Rational& r, const Rational&
s);
friend Rational operator* (const Rational& r, const Rational&
s);
friend Rational operator/ (const Rational& r, const Rational&
s);
// ASSUME: s != 0
// Comparison operators.
friend bool operator< (const
Rational& r, const Rational& s);
friend bool operator<= (const Rational& r, const Rational&
s);
friend bool operator> (const
Rational& r, const Rational& s);
friend bool operator>= (const Rational& r, const Rational&
s);
friend bool operator== (const Rational& r, const Rational& s);
friend bool operator!= (const Rational& r, const Rational& s);
// I/O operators.
friend ostream& operator<< (ostream& out, const
Rational& r);
// Inserts a rational number in the form n/d into out.
friend istream& operator>> (istream& in, Rational& r);
// Extracts items of the form n/d from in.
// r is assigned the value Rational(n/d).
// Modified assignment operators.
Rational& operator+= (const Rational& r);
Rational& operator-= (const Rational& r);
Rational& operator*= (const Rational& r);
Rational& operator/= (const Rational& r); // ASSUME: r != 0
// Conversion to a double
double doubleVal() const; //
FloaTing point value of this Rational
private:
int num_;
int denom_;
void reduce();
};
//FILE: RATIONAL.C
#include "rational.H"
int gcd(int x, int y)
{
if (x == 0)
return y;
if (y == 0)
return x;
int remainder;
do {
remainder = x % y;
x = y;
y = remainder;
} while (remainder > 0);
return x;
}
void Rational :: reduce()
{
if (denom_ < 0) {
denom_ = - denom_;
num_ = - num_;
}
int k;
if (num_ < 0)
k = gcd(- num_, denom_);
else
k = gcd(num_,denom_);
num_ /= k;
denom_ /= k;
}
Rational :: Rational(int n, int d)
:num_(n), denom_(d)
{
reduce();
}
Rational Rational :: operator-() const
{
return Rational(-num_,denom_);
}
Rational operator+(const Rational&
r, const Rational& s)
{
Rational result;
result.num_ = r.num_ * s.denom_ + r.denom_ * s.num_;
result.denom_ = r.denom_ * s.denom_;
result.reduce();
return result;
}
Rational operator-(const Rational&
r, const Rational& s)
{
Rational result;
result.num_ = r.num_ * s.denom_ - r.denom_ * s.num_;
result.denom_ = r.denom_ * s.denom_;
result.reduce();
return result;
}
Rational operator*(const Rational&
r, const Rational& s)
{
Rational result;
result.num_ = r.num_ * s.num_;
result.denom_ = r.denom_ * s.denom_;
result.reduce();
return result;
}
Rational operator/(const Rational&
r, const Rational& s)
{
Rational result;
result.num_ = r.num_ * s.denom_;
result.denom_ = r.denom_ * s.num_;
result.reduce();
return result;
}
bool operator< (const Rational&
r, const Rational& s)
{
return (r.num_ * s.denom_ < r.denom_ * s.denom_);
}
bool operator<= (const Rational&
r, const Rational& s)
{
return (r.num_ * s.denom_ <= r.denom_ * s.denom_);
}
bool operator> (const Rational&
r, const Rational& s)
{
return (r.num_ * s.denom_ > r.denom_ * s.denom_);
}
bool operator>= (const Rational&
r, const Rational& s)
{
return (r.num_ * s.denom_ >= r.denom_ * s.denom_);
}
bool operator== (const Rational& r,
const Rational& s)
{
return (r.num_ * s.denom_ == r.denom_ * s.num_);
}
bool operator!= (const Rational& r,
const Rational& s)
{
return (r.num_ * s.denom_ != r.denom_ * s.num_);
}
ostream&
operator<<(ostream& out, const Rational& r)
{
out << r.num_ << '/' << r.denom_; // int and char
insertion
return out;
}
istream& operator>>
(istream& in, Rational& r)
{
int num; // Numerator to be read
int den; //
Denominator to be read
char slash; // /
character between num and den
in >> num >> slash >> den;
r = Rational(num,den);
return in;
}
Rational& Rational :: operator+=
(const Rational & r)
{
num_ = r.num_ * denom_ + r.denom_ * num_;
denom_ *= r.denom_;
reduce();
return *this;
}
Rational& Rational :: operator-=
(const Rational & r)
{
num_ = r.num_ * denom_ - r.denom_ * num_;
denom_ *= r.denom_;
reduce();
return *this;
}
Rational& Rational :: operator*=
(const Rational & r)
{
num_ *= r.num_;
denom_ *= r.denom_;
reduce();
return *this;
}
Rational& Rational :: operator/=
(const Rational & r)
{
num_ *= r.denom_;
denom_ *= r.num_;
reduce();
return *this;
}
double Rational :: doubleVal() const
{
return num_/ double (denom_);
}
//*******************************************************************************
//FILE: VECTOR3D.H
#include <iostream.h>
// 3-dimensional vectors with real
components
class Vector3D {
public:
Vector3D(double x = 0, double y = 0, double z = 0); // Constructs
(x,y,z)
// Comparisons. (Two vectors are equal if their components match.)
friend bool operator==(const Vector3D& v, const Vector3D& w);
friend bool operator!=(const Vector3D& v, const Vector3D& w);
// Addition, subtraction, and unary minus.
friend Vector3D operator+(const Vector3D& v, const Vector3D& w);
friend Vector3D operator-(const Vector3D& v, const Vector3D& w);
Vector3D operator-() const;
// Dot product and scalar product.
friend double operator*(const Vector3D& v, const Vector3D&
w);
friend Vector3D operator*(double a, const Vector3D& w);
// Magnitude
double magnitude() const;
// Subscripting: access to individual components
double& operator[](int i);
// ASSUME: i is 0, 1, 2
double operator[](int i) const;
// ASSUME: i is 0, 1, 2
// Input and output
friend istream& operator>>(istream& in, Vector3D& v);
// Inputs data in the form (x,y,z), where x, y, z are
numeric.
friend ostream& operator<<(ostream& out, const
Vector3D& v);
// Outputs data in the form (x,y,z).
private:
enum {dimension_ = 3};
double component_[dimension_];
};
//FILE: VECTOR3D.C
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
#include "vector.H"
Vector3D :: Vector3D(double x, double
y, double z)
{ component_[0] = x;
component_[1] = y;
component_[2] = z;
}
bool operator==(const Vector3D& v,
const Vector3D& w)
{
for (int i = 0; i < Vector3D::dimension_; i++)
if (v.component_[i] != w.component_[i])
return false;
return true;
}
bool operator!=(const Vector3D& v,
const Vector3D& w)
{
return !(v == w);
}
Vector3D operator+(const Vector3D&
v, const Vector3D& w)
{
Vector3D result(v);
for(int i = 0; i < Vector3D::dimension_; i++)
result.component_[i] += w.component_[i];
return result;
}
Vector3D operator-(const Vector3D&
v, const Vector3D& w)
{
Vector3D result(v);
for(int i = 0; i < Vector3D::dimension_; i++)
result.component_[i] -= w.component_[i];
return result;
}
Vector3D Vector3D :: operator-() const
{
Vector3D result;
for(int i = 0; i < dimension_; i++)
result.component_[i] = -component_[i];
return result;
}
// Dot product
double operator*(const Vector3D& v,
const Vector3D& w)
{
double returnVal = 0.0;
for (int i = 0; i < Vector3D::dimension_; i++)
returnVal += v.component_[i] * w.component_[i];
return returnVal;
}
// Scalar product
Vector3D operator*(double a, const
Vector3D& v)
{
Vector3D temp(v); // temp is
a copy of c
for (int i = 0; i < Vector3D::dimension_; i++)
temp.component_[i] *= a;
return temp;
}
ostream&
operator<<(ostream& out, const Vector3D& v)
{
out << '(';
for (int i = 0; i < Vector3D::dimension_ - 1; i++)
out << v.component_[i] << ',';
out << v.component_[i] << ')';
return out;
}
istream& operator>>(istream&
in, Vector3D& v)
{
char punctuation; // to
read parentheses, commas
for (int i = 0; i < Vector3D::dimension_; i++)
in >> punctuation >> v.component_[i];
in >> punctuation;
return in;
}
double& Vector3D :: operator[](int i)
{
if (i < 0 || i >= dimension_) {
cerr << "Subscript range error";
exit(1);
}
return component_[i];
}
double Vector3D :: operator[](int i)
const
{
if (i < 0 || i >= dimension_) {
cerr << "Subscript range error";
exit(1);
}
return component_[i];
}
double Vector3D :: magnitude() const
{
double sum = 0; // sum of
squares of the components
for (int i = 0; Vector3D::dimension_; i++)
sum += component_[i] * component_[i];
return sqrt(sum);
}
//*******************************************************************************
//FILE: STRING.H
// A first class string type
class String {
public:
// Constructors and destructor
String(const char s[] = ""); // Constructs a deep copy of a
C-string.
//
ASSUME: s is a valid C-string.
String(const String& s);
// Constructs a deep copy of s.
~String(); //
Deallocates String memory.
// Assignment operators
String& operator= (const String& rhs); // Assigns a deep copy of rhs.
String& operator+= (const String& rhs); // Adds a deep copy of rhs on the
// end of this string.
char& operator[](int i);
// The element at subscript i.
// ASSUME: i < length of
the string
char operator[](int i) const;
// The element at subscript i.
// ASSUME: i < length of
the string
int length() const;
// Number of string characters.
const char* charString( ) const;
// C-String equivalent value.
// Comparison operators
friend bool operator== (const String& s, const String& t);
friend bool operator!= (const String& s, const String& t);
friend bool operator< (const
String& s, const String& t);
friend bool operator<= (const String& s, const String& t);
friend bool operator> (const
String& s, const String& t);
friend bool operator>= (const String& s, const String& t);
friend ostream& operator<<(ostream& out, const String&
s);
// Writes the C-string equivalent to out.
friend istream& operator>> (istream& in, String &
s);
// Reads at most 999 characters up to the next
newline from
// from in.
The newline is extracted but not assigned.
friend String operator+(const String& s, const String& t);
// A deep copy of s with a deep copy of t appended
to the end.
private:
char* info_;
};
//FILE: STRING.C
#include <string.h>
#include "string.H"
String:: String(const char s[])
{
info_ = new char[strlen(s) + 1];
// Leave room for the '\0'.
strcpy(info_, s);
// Copy from s to info.
}
String:: String(const String& s)
{
info_ = new char[strlen(s.info_) + 1]; // Allocate memory for the copy.
strcpy(info_, s.info_);
// Copy the argument's characters.
}
String :: ~String( )
{
delete [] info_; // Deallocate
the array.
}
String& String::operator= (const
String& rhs)
{
if (this != &rhs) { // Cover the case of s = s.
delete [] info_;
// Deallocate the old buffer.
info_ = new char[strlen(rhs.info_) +1];// Allocate memory for a new one.
strcpy(info_, rhs.info_);
// Copy the characters from the
} // right side to the left
return *this; // Return this object.
}
String& String :: operator+= (const
String& s)
{
char* temp = new char[strlen(info_) + strlen(s.info_) + 1]; // Create a
new
// array to hold the two string arrays.
strcpy(temp,info_); // Copy
the characters from this array into temp.
strcat(temp,s.info_); // Then
copy the characters of s.info_ into temp.
delete [] info_; //
Replace the old value for info_ by temp.
info_ = temp;
return *this;
}
String operator+ (const String& s,
const String& t)
{
String temp(s); // temp is a
copy of s.
temp += t; // Add t to
the end of temp.
return temp;
}
char& String::operator[](int i)
{
return info_[i];
}_
char String :: operator[](int i) const
{
return info_[i];
}
const char* String :: charString()
const
{
return info_;
}
ostream&
operator<<(ostream& out, const String& s)
{
out << s.charString();
return out;
}
istream& operator>>
(istream& in, String& s)
{
char buffer[1000]; //
Buffer to store the stream characters
in.getline(buffer,1000,'\n'); //
Remove up to 999 characters from in,
// up to and including first occurrence
// of '\n'. Store all but
'\n' in the
// buffer; terminate the buffer with '\0'.
s = String(buffer); //
Create a new String from the buffer and
// assign it to s.
return in;
}
int String :: length() const
{
return strlen(info_);
}
bool operator== (const String& s,
const String& t)
{
return strcmp(s.info_,t.info_) == 0;
}
bool operator!= (const String& s,
const String& t)
{
return strcmp(s.info_,t.info_) != 0;
}
bool operator< (const String& s, const String& t)
{
return strcmp(s.info_,t.info_) < 0;
}
bool operator<= (const String&
s, const String& t)
{
return strcmp(s.info_,t.info_) <= 0;
}
bool operator> (const String& s, const String& t)
{
return strcmp(s.info_,t.info_) > 0;
}
bool operator>= (const String&
s, const String& t)
{
return strcmp(s.info_,t.info_) >= 0;
}
//*******************************************************************************
//FILE: bcstring.h
#include "string.H"
// Bounds checked string class
// Any attempt to subscript past the
length of the string results in an error.
class BCString : public String {
public:
// Constructors, destructor, and assignment -- Never Inherited
BCString(const char s[] = ""); // Constructs a deep copy of a C-string
// ASSUME: s is a valid C-string)
BCString(const BCString& bcs);
// Constructs a deep copy of s
~BCString();
// Destructor string memory
BCString& operator= (const BCString& rhs); // Assigns a deep copy of rhs
// Remaining operators -- Inherited, but Modified Behavior Wanted
char& operator[] (int i);
// Character at subscript i; if i < 0 or
i > length , exit()is
invoked
char& operator[] (int i); const B; // Character at subscript i; if i
< 0 or
i > length , exit()is
ainvoed
int length() const; // Length of the string
friend operator+(const BCString& b, const BCString& c);
//
Returns the concatenation of b and c.
friend istream& operator>>(const BCString& b, const
BCString& c);
//
Returns at most 999 characters up to the next newline from
// from in.
Te newline is extracted but not assigned.
private:
int length_;
};
//FILE: BCSTRING.C
#include <string.h>
#include "BCString.H"
#include <stdlib.h>
BCString :: BCString(const char s[]) :
String(s), length_(strlen(s))
{ }
BCString :: BCString(const
BCString& bcs) : String(bcs), length_(bcs.length_)
{ }
BCString :: ~BCString()
{ }
BCString& BCString :: operator=
(const BCString& rhs)
{
String::operator=(rhs); // Line 1 -- call to base class assignment
length_ = rhs.length_;
// Line 2 -- ordinary int assignment
return *this;
}
char& BCString :: operator[](int i)
{
if (0 <= i && i < length_)
return String::operator[](i); //
calls char& String::operator[]()
else
exit(1);
}
char BCString :: operator[](int i)
const
{
if (0 <= i && i < length_)
return String::operator[](i); //
calls char String::operator[]() const
else
exit(1);
}
int BCString :: length() const
{
return length_;
}
BCString operator+(const BCString&
b, const BCString& c)
{
BCString ret(b); // Create a
return value out of the first argument.
ret += c; // Use the
BCString += operator.
return ret;
}
istream&
operator>>(istream& in, BCString& bc)
{
String s; //
Temporary string for getting the input.
in >> s;
// String input operator.
bc = BCString(s.charString()); // Assign bc a BCString constructed from
// the temporary String's C-string.
return in;
}
//*******************************************************************************
//FILE: DOOR.H
#include "string.H"
// A generic door class
class Door {
public:
Door(); //
Constructs a shut door.
bool isOpen() const; // Is the
door open?
void open(); // Opens
the door, if possible.
void close(); // Shuts
the door.
protected:
bool shut_;
};
// A lockable door class
class LockableDoor : public Door {
public:
LockableDoor(); //
Constructs a locked, shut door.
bool isLocked() const; // Is
the door locked?
void open(); // Opens
the door if it is not locked.
void lock(); // Locks
the door.
void unlock(); //
Unlocks the door
protected:
bool locked_;
};
// A combination lock door
// Combinations are single integers
class CombinationLockDoor : public
LockableDoor {
public:
CombinationLockDoor (int c = 0); // Constructs a door with combination
c
void unlock(int c = 0);
// Attempts to unlock the door using
// combination c. Does nothing if c
// is not the correct combination.
protected:
int combination_;
};
// A lockable door that requires a
password to unlock
class PasswordDoor : public
LockableDoor {
public:
PasswordDoor(const char c[] = ""); // Creates a door with
password c
void unlock(const char c[] = ""); // Attempts to unlock the door using
// password c. Does nothing
if c
// is not the correct password.
protected:
String password_;
};
//FILE: DOOR.C
#include "door.H"
Door :: Door() : shut_(true)
{ }
bool Door :: isOpen() const
{
return !shut_;
}
void Door :: open()
{
shut_ = false; // By
default, it is always possible to open.
}
void Door :: close()
{
shut_ = true;
}
LockableDoor :: LockableDoor() :
Door(), locked_(true)
{ }
bool LockableDoor :: isLocked() const
{
return locked_;
}
void LockableDoor :: lock()
{
locked_ = true;
}
void LockableDoor :: unlock()
{
locked_ = false;
}
void LockableDoor :: open()
{
if (!locked_)
Door :: open(); // could
have used: shut_ = false;
}
CombinationLockDoor::CombinationLockDoor
(int c) : LockableDoor(),
combination_(c)
{ }
void CombinationLockDoor :: unlock(int
c)
{
if (c == combination_)
LockableDoor::unlock(); //
could use: locked_ = false;
}
PasswordDoor :: PasswordDoor(const char
c[]) : LockableDoor(),
password_(c)
{ }
void PasswordDoor :: unlock(const char c[])
{
if (c == password_)
locked_ = false;
}
//*******************************************************************************
//FILE: CKRADIO.H
// A simple clock class
class Clock {
public:
Clock(int hh = 24, int mm = 0, int ss = 0); // Constructs a 24-hour
Clock
// with time hh:mm:ss
int hour() const; // Hour of time
int minute() const; // Minute of time
int second() const; // Second of time
void setNext(); // Advance the time by 1 second
void reset(int hh, int mm, int ss); // Time becomes hh:mm:ss
protected:
int hour_;
int minute_;
int second_;
};
// A simple radio class
class Radio {
public:
Radio(double n = 99., bool play = false); // Constructs a Radio tuned to
// frequency n and turned on if
// play is true, off if play is
// false
double frequency() const; // Frequency on the dial
bool isOn() const; // True when the radio is on
void flipSwitch(); // Switches the radio from
off/on
// to on/off
void changeDial(double n); // Frequency is reset to n
protected:
double frequency_;
bool on_;
};
// A simple clock radio class
class ClockRadio : public Clock, public
Radio {
public:
ClockRadio (int hh = 24, int mm = 0, int ss = 0, double n = 99.,
bool play = false);
// Constructs a ClockRadio with time hh:mm:ss, tuned to
frequency n,
// and turned off if play is false and on if play is true.
};
//FILE: CKRADIO.C
#include "ckRadio.H"
Clock::Clock(int hh, int mm, int
ss):hour_(hh),minute_(mm),second_(ss)
{}
int Clock::hour() const
{ return hour_;}
int Clock::minute() const
{ return minute_;}
int Clock::second() const
{ return second_;}
void Clock::setNext()
{
second_++;
if (second_ == 60) {
second_ = 0;
minute_++;
if (minute_ == 60) {
minute_ = 0;
hour_++;
if (hour_ == 25)
hour_ = 1;
}
}
}
void Clock::reset(int hh, int mm, int
ss)
{
hour_ = hh;
minute_ = mm;
second_ = ss;
}
Radio :: Radio(double n, bool
play):frequency_(n), on_(play)
{ }
double Radio :: frequency() const
{
return frequency_;
}
bool Radio :: isOn() const
{
return on_;
}
void Radio :: flipSwitch()
{
on_
= !on_;
}
void Radio :: changeDial(double n)
{
frequency_ = n;
}
ClockRadio :: ClockRadio (int hh, int
mm, int ss, double n, bool on)
: Clock(hh,mm,ss), Radio(n,on)
{ }
//*******************************************************************************
// FILE: counter.H
// A simple counting class
class Counter {
public:
Counter();
// Constructs a counter set to 0.
int value() const;
// Current counter value.
void nvPrint() const;
// Prints the counter value.
// virtual member functions
virtual void print() const;
// Prints the count.
virtual void increment(); // Increments the counter one unit.
virtual void decrement();
// Decrements the counter one unit.
protected:
int count_;
};
// A counter which does its counting
modulo a positive integer base.
class ModCounter : public Counter {
public:
ModCounter(int b = 10); // Constructs a counter set to 0 to count modulo
b
//
ASSUME: b > 1
void nvPrint() const; // Prints
the values of the ModCounter.
void print() const; // Prints
the values of the ModCounter.
int base() const; // Base
value.
Void increment(); //
Increments the count one unit modulo the base.
void decrement(); //
Decrements the count one unit modulo the base.
protected:
int base_;
};
// A counter that keeps its count
within a fixed range of values.
class RangeCounter : public Counter {
public:
RangeCounter(int b = 0, int t = 1000);
// Creates a counter set to 0 which
//
counts from a minimum of b to maximum of t.
//
ASSUME: 0 <= b <= t
void nvPrint() const; //
Prints the values for the RangeCounter.
void print() const; //
Prints the values for the RangeCounter.
int top() const; //
Maximum possible counter value.
int bottom() const; //
Minimum possible counter value.
void increment(); //
Increments the count by 1 up to the maximum.
void decrement(); //
Decrements the count by 1 down to the minimum.
protected:
int bottomOfRange_;
int topOfRange_;
};
// A counter with a fixed range that
can detect when an overflow occurs.
class CounterWithOverflow : public
RangeCounter {
public:
CounterWithOverflow(int b = 0, int t = 1000);
// Creates a counter set to 0 which
//
counts from a minimum of b to maximum of t.
//
ASSUME: 0 <= b <= t
void increment(); //
Increments the count by 1 up to the maximum.
void print() const; // Prints
the currrent values.
bool overflow() const; // Has overflow occurred?
protected:
bool overflow_;
};
//FILE: COUNTER.C
#include "counter.H"
#include <iostream.h>
Counter :: Counter() : count_(0)
{ }
int Counter :: value() const
{
return count_;
}
void Counter :: nvPrint() const
{
cout << "The count is " << count_ << endl;
}
void Counter :: print() const
{
nvPrint();
}
void Counter :: increment()
{
count_++;
}
void Counter :: decrement()
{
count_--;
}
ModCounter :: ModCounter(int b) :
base_(b)
{ }
void ModCounter :: nvPrint() const
{
cout << "The count is " << count_ << "
modulo " << base_ << endl;
}
void ModCounter :: print() const
{
nvPrint(); // invokes ModCounter::nvPrint()
}
int ModCounter :: base() const
{
return base_;
}
void ModCounter :: increment()
{
count_ = (count_ + 1) % base_;
}
void ModCounter :: decrement()
{
count_--;
if (count_ < 0)
count_ = base_ - 1;
}
RangeCounter :: RangeCounter(int b, int
t) : bottomOfRange_(b), topOfRange_(t)
{ }
int RangeCounter :: top() const
{
return topOfRange_;
}
int RangeCounter :: bottom() const
{
return bottomOfRange_;
}
void RangeCounter :: increment()
{
if (count_ < topOfRange_)
count_++;
}
void RangeCounter :: decrement()
{
if (count_ > bottomOfRange_)
count_--;
}
void RangeCounter :: nvPrint() const
{
cout << "The count is " << count_ << ",
top of range: " << topOfRange_
<< ", bottom of range " <<
bottomOfRange_ << endl;
}
void RangeCounter :: print() const
{
nvPrint();
}
CounterWithOverflow ::
CounterWithOverflow (int b, int t) : RangeCounter(b,t)
{ }
void CounterWithOverflow :: increment()
{
if (count_ == topOfRange_)
overflow_ = true;
else
count_++;
}
void CounterWithOverflow :: print()
const
{
cout <<"OVFL: ";
RangeCounter::print();
}
bool CounterWithOverflow :: overflow()
const
{
return overflow_;
}
//*******************************************************************************
©DrB,1997-2000 All Rights Reserved.
Original Code
borrowed from Perry & Levin. Web
Design & Use for non-commercial, student use only.