C++大学教程(第七版)课后习题答案第十二十三十四章

549 阅读7分钟

第十二章

12.12(工资发放系统纠正)

//CommissionEmployee.h
#ifndef COMMISSION_H
#define COMMISSION_H

#include <string>
using namespace std;

class CommissionEmployee
{
public:
   CommissionEmployee( const string &, const string &, const string &, 
      double = 0.0, double = 0.0 ); 
   void setFirstName( const string & ); 
   string getFirstName() const;
   void setLastName( const string & );
   string getLastName() const;
   void setSocialSecurityNumber( const string & );
   string getSocialSecurityNumber() const;
   void setGrossSales( double );
   double getGrossSales() const;
   void setCommissionRate( double ); 
   double getCommissionRate() const;
   double earnings() const;
   void print() const;
private:
   string firstName;
   string lastName;
   string socialSecurityNumber;
   double grossSales;
   double commissionRate;
};

#endif
//CommissionEmployee.cpp
#include <iostream>
#include "CommissionEmployee.h"
using namespace std;

CommissionEmployee::CommissionEmployee( 
   const string &first, const string &last, const string &ssn, 
   double sales, double rate )
   : firstName( first ), lastName( last ), socialSecurityNumber( ssn )
{
   setGrossSales( sales );
   setCommissionRate( rate );
}

void CommissionEmployee::setFirstName( const string &first )
{
   firstName = first;
}

string CommissionEmployee::getFirstName() const
{
   return firstName; 
}

void CommissionEmployee::setLastName( const string &last )
{
   lastName = last; // should validate
}

string CommissionEmployee::getLastName() const
{
   return lastName;
}

void CommissionEmployee::setSocialSecurityNumber( const string &ssn )
{
   socialSecurityNumber = ssn; // should validate
}

string CommissionEmployee::getSocialSecurityNumber() const
{
   return socialSecurityNumber;
}

void CommissionEmployee::setGrossSales( double sales )
{
   grossSales = ( sales < 0.0 ) ? 0.0 : sales;
}

double CommissionEmployee::getGrossSales() const
{
   return grossSales;
}

void CommissionEmployee::setCommissionRate( double rate )
{
   commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
}

double CommissionEmployee::getCommissionRate() const
{
   return commissionRate;
}

double CommissionEmployee::earnings() const
{
   return getCommissionRate() * getGrossSales();
}

void CommissionEmployee::print() const
{
   cout << "commission employee: " 
      << getFirstName() << ' ' << getLastName() 
      << "\nsocial security number: " << getSocialSecurityNumber() 
      << "\ngross sales: " << getGrossSales()
      << "\ncommission rate: " << getCommissionRate();
}
#ifndef BASEPLUS_H
#define BASEPLUS_H

#include <string>
#include "CommissionEmployee.h"
using namespace std;

class BasePlusCommissionEmployee
{
public:
   BasePlusCommissionEmployee( const string &, const string &, 
      const string &, double = 0.0, double = 0.0, double = 0.0 );
   void setFirstName( const string & );
   string getFirstName() const; 
   void setLastName( const string & );
   string getLastName() const;
   void setSocialSecurityNumber( const string & );
   string getSocialSecurityNumber() const;
   void setGrossSales( double ); 
   double getGrossSales() const; 
   void setCommissionRate( double );
   double getCommissionRate() const;
   void setBaseSalary( double ); 
   double getBaseSalary() const;
   double earnings() const;
   void print() const; 
private:
   double baseSalary; 
   CommissionEmployee commissionEmployee; 
};

#endif
//BasePlusCommissionEmployee.cpp
#include <iostream>
#include "BasePlusCommissionEmployee.h"
using namespace std;

BasePlusCommissionEmployee::BasePlusCommissionEmployee(
   const string &first, const string &last, const string &ssn,
   double sales, double rate, double salary )
   : commissionEmployee( first, last, ssn, sales, rate )
{
   setBaseSalary( salary );
}

void BasePlusCommissionEmployee::setFirstName( const string &first )
{
   commissionEmployee.setFirstName( first );
}

string BasePlusCommissionEmployee::getFirstName() const
{
   return commissionEmployee.getFirstName();
}

void BasePlusCommissionEmployee::setLastName( const string &last )
{
   commissionEmployee.setLastName( last );
}

string BasePlusCommissionEmployee::getLastName() const
{
   return commissionEmployee.getLastName();
}

void BasePlusCommissionEmployee::setSocialSecurityNumber( 
   const string &ssn )
{
   commissionEmployee.setSocialSecurityNumber( ssn );
}

string BasePlusCommissionEmployee::getSocialSecurityNumber() const
{
   return commissionEmployee.getSocialSecurityNumber();
}

void BasePlusCommissionEmployee::setGrossSales( double sales )
{
   commissionEmployee.setGrossSales( sales );
}

double BasePlusCommissionEmployee::getGrossSales() const
{
   return commissionEmployee.getGrossSales();
}

void BasePlusCommissionEmployee::setCommissionRate( double rate )
{
   commissionEmployee.setCommissionRate( rate );
}

double BasePlusCommissionEmployee::getCommissionRate() const
{
   return commissionEmployee.getCommissionRate();
}

void BasePlusCommissionEmployee::setBaseSalary( double salary )
{
   baseSalary = ( salary < 0.0 ) ? 0.0 : salary;
}

double BasePlusCommissionEmployee::getBaseSalary() const
{
   return baseSalary;
}

double BasePlusCommissionEmployee::earnings() const
{
   return getBaseSalary() + commissionEmployee.earnings();
}

void BasePlusCommissionEmployee::print() const
{
   cout << "base-salaried ";
   commissionEmployee.print();   
   cout << "\nbase salary: " << getBaseSalary();
}
//main.cpp
#include <iostream>
#include <iomanip>
#include "BasePlusCommissionEmployee.h" 
using namespace std;

int main()
{
   BasePlusCommissionEmployee 
      employee( "Bob", "Lewis", "333-33-3333", 5000, .04, 300 );
   cout << fixed << setprecision( 2 );
   cout << "Employee information obtained by get functions: \n" 
      << "\nFirst name is " << employee.getFirstName() 
      << "\nLast name is " << employee.getLastName() 
      << "\nSocial security number is " 
      << employee.getSocialSecurityNumber() 
      << "\nGross sales is " << employee.getGrossSales() 
      << "\nCommission rate is " << employee.getCommissionRate()
      << "\nBase salary is " << employee.getBaseSalary() << endl;
   employee.setBaseSalary( 1000 );
   cout << "\nUpdated employee information output by print function: \n" << endl;
   employee.print();
   cout << "\n\nEmployee's earnings: $" << employee.earnings() << endl;
}

12.13(Package继承层次)

//Package.h
#ifndef PACKAGE_H
#define PACKAGE_H

#include <string>
using namespace std;

class Package
{
public:
   Package( const string &, const string &, const string &, 
      const string &, int, const string &, const string &, const string &, 
      const string &, int, double, double );
   void setSenderName( const string & );
   string getSenderName() const;
   void setSenderAddress( const string & );
   string getSenderAddress() const;
   void setSenderCity( const string & );
   string getSenderCity() const;
   void setSenderState( const string & );
   string getSenderState() const;
   void setSenderZIP( int );
   int getSenderZIP() const;
   void setRecipientName( const string & );
   string getRecipientName() const;
   void setRecipientAddress( const string & );
   string getRecipientAddress() const;
   void setRecipientCity( const string & );
   string getRecipientCity() const;
   void setRecipientState( const string & );
   string getRecipientState() const;
   void setRecipientZIP( int );
   int getRecipientZIP() const;
   void setWeight( double );
   double getWeight() const;
   void setCostPerOunce( double );
   double getCostPerOunce() const;
   double calculateCost() const;
private:
   string senderName;
   string senderAddress;
   string senderCity;
   string senderState;
   int senderZIP;
   string recipientName;
   string recipientAddress;
   string recipientCity;
   string recipientState;
   int recipientZIP;
   double weight;
   double costPerOunce;
};

#endif
//Package.cpp
#include "Package.h"

Package::Package( const string &sName, const string &sAddress, 
   const string &sCity, const string &sState, int sZIP, 
   const string &rName, const string &rAddress, const string &rCity, 
   const string &rState, int rZIP, double w, double cost )
   : senderName( sName ), senderAddress( sAddress ), senderCity( sCity ),
     senderState( sState ), senderZIP( sZIP ), recipientName( rName ), 
     recipientAddress( rAddress ), recipientCity( rCity ), 
     recipientState( rState ), recipientZIP( rZIP )
{
   setWeight( w );
   setCostPerOunce( cost );
}

void Package::setSenderName( const string &name )
{
    senderName = name;
}

string Package::getSenderName() const
{
   return senderName;
}

void Package::setSenderAddress( const string &address )
{
   senderAddress = address;
}

string Package::getSenderAddress() const
{
   return senderAddress;
}

void Package::setSenderCity( const string &city )
{
   senderCity = city;
}

string Package::getSenderCity() const
{
   return senderCity;
}

void Package::setSenderState( const string &state )
{
   senderState = state;
}

string Package::getSenderState() const
{
   return senderState;
}

void Package::setSenderZIP( int zip )
{
   senderZIP = zip;
}

int Package::getSenderZIP() const
{
   return senderZIP;
}

void Package::setRecipientName( const string &name )
{
    recipientName = name;
}

string Package::getRecipientName() const
{
   return recipientName;
}

void Package::setRecipientAddress( const string &address )
{
   recipientAddress = address;
}

string Package::getRecipientAddress() const
{
   return recipientAddress;
}

void Package::setRecipientCity( const string &city )
{
   recipientCity = city;
}

string Package::getRecipientCity() const
{
   return recipientCity;
}

void Package::setRecipientState( const string &state )
{
   recipientState = state;
}

string Package::getRecipientState() const
{
   return recipientState;
}

void Package::setRecipientZIP( int zip )
{
   recipientZIP = zip;
}

int Package::getRecipientZIP() const
{
   return recipientZIP;
}

void Package::setWeight( double w )
{
   weight = ( w < 0.0 ) ? 0.0 : w;
}

double Package::getWeight() const
{
   return weight;
}

void Package::setCostPerOunce( double cost )
{
   costPerOunce = ( cost < 0.0 ) ? 0.0 : cost;
}

double Package::getCostPerOunce() const
{
   return costPerOunce;
}
double Package::calculateCost() const
{
   return getWeight() * getCostPerOunce();
}
//OvernightPackage.h
#ifndef OVERNIGHT_H
#define OVERNIGHT_H

#include "Package.h"

class OvernightPackage : public Package
{
public:
    OvernightPackage(const string&, const string&, const string&,
        const string&, int, const string&, const string&, const string&,
        const string&, int, double, double, double);
    void setOvernightFeePerOunce(double)
    double getOvernightFeePerOunce() const;
    double calculateCost() const;
private:
    double overnightFeePerOunce;
};

#endif
//OvernightPackage.cpp
#include "OvernightPackage.h"

OvernightPackage::OvernightPackage(const string& sName,
    const string& sAddress, const string& sCity, const string& sState,
    int sZIP, const string& rName, const string& rAddress,
    const string& rCity, const string& rState, int rZIP,
    double w, double cost, double fee)
    : Package(sName, sAddress, sCity, sState, sZIP,
        rName, rAddress, rCity, rState, rZIP, w, cost)
{
    setOvernightFeePerOunce(fee);
}

void OvernightPackage::setOvernightFeePerOunce(double overnightFee)
{
    overnightFeePerOunce = (overnightFee < 0.0) ? 0.0 : overnightFee;
}

double OvernightPackage::getOvernightFeePerOunce() const
{
    return overnightFeePerOunce;
}

double OvernightPackage::calculateCost() const
{
    return getWeight() * (getCostPerOunce() + getOvernightFeePerOunce());
}
//TwoDayPackage.h
#ifndef TWODAY_H
#define TWODAY_H

#include "Package.h"

class TwoDayPackage : public Package
{
public:
    TwoDayPackage(const string&, const string&, const string&,
        const string&, int, const string&, const string&, const string&,
        const string&, int, double, double, double);
    void setFlatFee(double);
    double getFlatFee() const;
    double calculateCost() const;
private:
    double flatFee;
};

#endif
//TwoDayPackage.cpp
#include "TwoDayPackage.h"

TwoDayPackage::TwoDayPackage(const string& sName,
    const string& sAddress, const string& sCity, const string& sState,
    int sZIP, const string& rName, const string& rAddress,
    const string& rCity, const string& rState, int rZIP,
    double w, double cost, double fee)
    : Package(sName, sAddress, sCity, sState, sZIP,
        rName, rAddress, rCity, rState, rZIP, w, cost)
{
    setFlatFee(fee);
}

void TwoDayPackage::setFlatFee( double fee )
{
   flatFee = ( fee < 0.0 ) ? 0.0 : fee;
}

double TwoDayPackage::getFlatFee() const
{
   return flatFee;
}

double TwoDayPackage::calculateCost() const
{
   return Package::calculateCost() + getFlatFee();
}
//main.cpp
#include <iostream>
#include <iomanip>
#include "Package.h"
#include "TwoDayPackage.h"
#include "OvernightPackage.h"
using namespace std;

int main()
{
    Package package1("Lou Brown", "1 Main St", "Boston", "MA", 11111,
        "Mary Smith", "7 Elm St", "New York", "NY", 22222, 8.5, .5);
    TwoDayPackage package2("Lisa Klein", "5 Broadway", "Somerville", "MA",
        33333, "Bob George", "21 Pine Rd", "Cambridge", "MA", 44444,
        10.5, .65, 2.0);
    OvernightPackage package3("Ed Lewis", "2 Oak St", "Boston", "MA",
        55555, "Don Kelly", "9 Main St", "Denver", "CO", 66666,
        12.25, .7, .25);
    cout << fixed << setprecision(2);
    cout << "Package 1:\n\nSender:\n" << package1.getSenderName()
        << '\n' << package1.getSenderAddress() << '\n'
        << package1.getSenderCity() << ", " << package1.getSenderState()
        << ' ' << package1.getSenderZIP();
    cout << "\n\nRecipient:\n" << package1.getRecipientName()
        << '\n' << package1.getRecipientAddress() << '\n'
        << package1.getRecipientCity() << ", "
        << package1.getRecipientState() << ' '
        << package1.getRecipientZIP();
    cout << "\n\nCost: $" << package1.calculateCost() << endl;
    cout << "\nPackage 2:\n\nSender:\n" << package2.getSenderName()
        << '\n' << package2.getSenderAddress() << '\n'
        << package2.getSenderCity() << ", " << package2.getSenderState()
        << ' ' << package2.getSenderZIP();
    cout << "\n\nRecipient:\n" << package2.getRecipientName()
        << '\n' << package2.getRecipientAddress() << '\n'
        << package2.getRecipientCity() << ", "
        << package2.getRecipientState() << ' '
        << package2.getRecipientZIP();
    cout << "\n\nCost: $" << package2.calculateCost() << endl;
    cout << "\nPackage 3:\n\nSender:\n" << package3.getSenderName()
        << '\n' << package3.getSenderAddress() << '\n'
        << package3.getSenderCity() << ", " << package3.getSenderState()
        << ' ' << package3.getSenderZIP();
    cout << "\n\nRecipient:\n" << package3.getRecipientName()
        << '\n' << package3.getRecipientAddress() << '\n'
        << package3.getRecipientCity() << ", "
        << package3.getRecipientState() << ' '
        << package3.getRecipientZIP();
    cout << "\n\nCost: $" << package3.calculateCost() << endl;
}

12.14(使用账户层次的多态银行程序)

//Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H

class Account
{
public:
   Account( double );
   void credit( double );
   bool debit( double );
   void setBalance( double );
   double getBalance();
private:
   double balance;
};

#endif
//Account.cpp
#include <iostream>
#include "Account.h"
using namespace std;

Account::Account( double initialBalance )
{
   if ( initialBalance >= 0.0 )
      balance = initialBalance;
   else
   {
      cout << "Error: Initial balance cannot be negative." << endl;
      balance = 0.0;
   }
}

void Account::credit( double amount )
{
   balance = balance + amount;
}

bool Account::debit( double amount )
{
   if ( amount > balance )
   {
      cout << "Debit amount exceeded account balance." << endl;
      return false;
   }
   else
   {
      balance = balance - amount;
      return true;
   }
}

void Account::setBalance( double newBalance )
{
   balance = newBalance;
}

double Account::getBalance()
{
   return balance;
}
//CheckingAccount.h
#ifndef CHECKING_H
#define CHECKING_H

#include "Account.h"

class CheckingAccount : public Account
{
public:
   CheckingAccount( double, double );
   void credit( double );
   bool debit( double );
private:
   double transactionFee; 
   void chargeFee();
};

#endif
//CheckingAccount.cpp
#include <iostream>
#include "CheckingAccount.h"
using namespace std;

CheckingAccount::CheckingAccount( double initialBalance, double fee )
   : Account( initialBalance )
{
   transactionFee = ( fee < 0.0 ) ? 0.0 : fee;
}

void CheckingAccount::credit( double amount )
{
   Account::credit( amount );
   chargeFee();
}

bool CheckingAccount::debit( double amount )
{
   bool success = Account::debit( amount );
   if ( success )
   {
      chargeFee();
      return true;
   }
   else
      return false;
}

void CheckingAccount::chargeFee()
{
   Account::setBalance( getBalance() - transactionFee );
   cout << "$" << transactionFee << " transaction fee charged." << endl;
}
//SavingsAccount.h
#ifndef SAVINGS_H
#define SAVINGS_H

#include "Account.h"

class SavingsAccount : public Account
{
public:
   SavingsAccount( double, double );
   double calculateInterest();
private:
   double interestRate;
};

#endif
SavingsAccount.cpp
#include "SavingsAccount.h"

SavingsAccount::SavingsAccount(double initialBalance, double rate)
	: Account(initialBalance)
{
	interestRate = (rate < 0.0) ? 0.0 : rate;
}

double SavingsAccount::calculateInterest()
{
	return getBalance() * interestRate;
}
//main.cpp
#include <iostream>
#include <iomanip>
#include "Account.h"
#include "SavingsAccount.h"
#include "CheckingAccount.h"
using namespace std;

int main()
{
    Account account1(50.0);
    SavingsAccount account2(25.0, .03);
    CheckingAccount account3(80.0, 1.0);
    cout << fixed << setprecision(2);
    cout << "account1 balance: $" << account1.getBalance() << endl;
    cout << "account2 balance: $" << account2.getBalance() << endl;
    cout << "account3 balance: $" << account3.getBalance() << endl;
    cout << "\nAttempting to debit $25.00 from account1." << endl;
    account1.debit(25.0);
    cout << "\nAttempting to debit $30.00 from account2." << endl;
    account2.debit(30.0);
    cout << "\nAttempting to debit $40.00 from account3." << endl;
    account3.debit(40.0);
    cout << "\naccount1 balance: $" << account1.getBalance() << endl;
    cout << "account2 balance: $" << account2.getBalance() << endl;
    cout << "account3 balance: $" << account3.getBalance() << endl;
    cout << "\nCrediting $40.00 to account1." << endl;
    account1.credit(40.0);
    cout << "\nCrediting $65.00 to account2." << endl;
    account2.credit(65.0);
    cout << "\nCrediting $20.00 to account3." << endl;
    account3.credit(20.0);
    cout << "\naccount1 balance: $" << account1.getBalance() << endl;
    cout << "account2 balance: $" << account2.getBalance() << endl;
    cout << "account3 balance: $" << account3.getBalance() << endl;
    double interestEarned = account2.calculateInterest();
    cout << "\nAdding $" << interestEarned << " interest to account2."
        << endl;
    account2.credit(interestEarned);
    cout << "\nNew account2 balance: $" << account2.getBalance() << endl;
}

12.15(工资发放系统纠正)

//Date.h
#ifndef DATE_H
#define DATE_H

#include <iostream>
using namespace std;

class Date
{
   friend ostream &operator<<( ostream &, const Date & );
public:
   Date( int m = 1, int d = 1, int y = 1900 );
   void setDate( int, int, int );
   Date &operator++();
   Date operator++( int ); // postfix increment operator
   const Date &operator+=( int );
   bool leapYear( int ) const;
   bool endOfMonth( int ) const;
   int getMonth() const;
private:
   int month;
   int day;
   int year;
   static const int days[];
   void helpIncrement();
};

#endif
//Date.cpp
#include <iostream>
#include "Date.h"

const int Date::days[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Date::Date( int m, int d, int y ) 
{ 
   setDate( m, d, y ); 
}

void Date::setDate( int mm, int dd, int yy )
{
   month = ( mm >= 1 && mm <= 12 ) ? mm : 1;
   year = ( yy >= 1900 && yy <= 2100 ) ? yy : 1900;
   if ( month == 2 && leapYear( year ) )
      day = ( dd >= 1 && dd <= 29 ) ? dd : 1;
   else
      day = ( dd >= 1 && dd <= days[ month ] ) ? dd : 1;
}

Date &Date::operator++()
{
   helpIncrement();
   return *this;
}
Date Date::operator++( int )
{
   Date temp = *this;
   helpIncrement(); 
   return temp;
}

const Date &Date::operator+=( int additionalDays )
{
   for ( int i = 0; i < additionalDays; i++ )
      helpIncrement();
   return *this;
}

bool Date::leapYear( int testYear ) const
{
   if ( testYear % 400 == 0 || 
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
      return true;
   else
      return false;
}

int Date::getMonth() const
{
   return month;
}

bool Date::endOfMonth( int testDay ) const
{
   if ( month == 2 && leapYear( year ) )
      return testDay == 29;
   else
      return testDay == days[ month ];
}

void Date::helpIncrement()
{
   if ( !endOfMonth( day ) )
      day++;
   else 
      if ( month < 12 )
      {
         month++; 
         day = 1;
      }
      else
      {
         year++;
         month = 1; 
         day = 1;
     

ostream &operator<<( ostream &output, const Date &d )
{
   static char *monthName[ 13 ] = { "", "January", "February",
      "March", "April", "May", "June", "July", "August",
      "September", "October", "November", "December" };
   output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
   return output;
}
//Employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include <string>
#include "Date.h"
using namespace std;

class Employee 
{
public:
   Employee( const string &, const string &, const string &, 
      int, int, int );
   void setFirstName( const string & );
   string getFirstName() const;
   void setLastName( const string & );
   string getLastName() const;
   void setSocialSecurityNumber( const string & );
   string getSocialSecurityNumber() const;
   void setBirthDate( int, int, int );
   Date getBirthDate() const;
   virtual double earnings() const = 0; 
   virtual void print() const;
private:
   string firstName;
   string lastName;
   string socialSecurityNumber;
   Date birthDate;
};
//Employee.cpp
#include <iostream>
#include "Employee.h" // Employee class definition
using namespace std;

Employee::Employee( const string &first, const string &last,
   const string &ssn, int month, int day, int year )
   : firstName( first ), lastName( last ), socialSecurityNumber( ssn ),
     birthDate( month, day, year )
{
}

void Employee::setFirstName( const string &first ) 
{ 
   firstName = first;  
}

string Employee::getFirstName() const 
{ 
   return firstName;  
}

void Employee::setLastName( const string &last )
{
   lastName = last;   
}

string Employee::getLastName() const
{
   return lastName;   
}

void Employee::setSocialSecurityNumber( const string &ssn )
{
   socialSecurityNumber = ssn;
}

string Employee::getSocialSecurityNumber() const
{
   return socialSecurityNumber;   
}

void Employee::setBirthDate( int month, int day, int year )
{
   birthDate.setDate( month, day, year );
}

Date Employee::getBirthDate() const
{
   return birthDate;
}
void Employee::print() const
{ 
   cout << getFirstName() << ' ' << getLastName() 
      << "\nbirthday: " << getBirthDate()
      << "\nsocial security number: " << getSocialSecurityNumber(); 
}
#ifndef COMMISSION_H
#define COMMISSION_H

#include "Employee.h"

class CommissionEmployee : public Employee
{
public:
    CommissionEmployee(const string&, const string&,
        const string&, int, int, int, double = 0.0, double = 0.0);
    void setCommissionRate(double);
    double getCommissionRate() const;
    void setGrossSales(double);
    double getGrossSales() const;
    virtual double earnings() const;
    virtual void print() const;
private:
    double grossSales;
    double commissionRate;
};
#endif
//CommissionEmployee.cpp
#include <iostream>
#include "CommissionEmployee.h"
using namespace std;
 
CommissionEmployee::CommissionEmployee( const string &first, 
   const string &last, const string &ssn, int month, int day, int year,
   double sales, double rate )
   : Employee( first, last, ssn, month, day, year )  
{
   setGrossSales( sales );
   setCommissionRate( rate );
}

void CommissionEmployee::setCommissionRate( double rate )
{ 
    commissionRate = ( ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0 );
}

double CommissionEmployee::getCommissionRate() const
{
    return commissionRate;
}

void CommissionEmployee::setGrossSales( double sales ) 
{ 
   grossSales = ( ( sales < 0.0 ) ? 0.0 : sales ); 
}

double CommissionEmployee::getGrossSales() const
{
    return grossSales;
}

double CommissionEmployee::earnings() const
{ 
   return getCommissionRate() * getGrossSales(); 
}

void CommissionEmployee::print() const
{
   cout << "commission employee: ";
   Employee::print(); // code reuse
   cout << "\ngross sales: " << getGrossSales() 
      << "; commission rate: " << getCommissionRate();
}
//SalariedEmployee.h
#ifndef SALARIED_H
#define SALARIED_H

#include "Employee.h"

class SalariedEmployee : public Employee
{
public:
    SalariedEmployee(const string&, const string&,
        const string&, int, int, int, double = 0.0);
    void setWeeklySalary(double);
    double getWeeklySalary() const;
    virtual double earnings() const;
    virtual void print() const;
private:
    double weeklySalary;
};

#endif
//SalariedEmployee.cpp
#include <iostream>
#include "SalariedEmployee.h"
using namespace std;

SalariedEmployee::SalariedEmployee( const string &first, 
   const string &last, const string &ssn, int month, int day, int year, 
   double salary )
   : Employee( first, last, ssn, month, day, year )
{ 
   setWeeklySalary( salary ); 
}

void SalariedEmployee::setWeeklySalary( double salary )
{ 
   weeklySalary = ( salary < 0.0 ) ? 0.0 : salary; 
}

double SalariedEmployee::getWeeklySalary() const
{
   return weeklySalary;
}

double SalariedEmployee::earnings() const 
{ 
   return getWeeklySalary(); 
}

void SalariedEmployee::print() const
{
   cout << "salaried employee: ";
   Employee::print();
   cout << "\nweekly salary: " << getWeeklySalary();
}
//HourlyEmployee.h
#ifndef HOURLY_H
#define HOURLY_H

#include "Employee.h"

class HourlyEmployee : public Employee 
{
public:
   static const int hoursPerWeek = 168; 
   HourlyEmployee( const string &, const string &, 
      const string &, int, int, int, double = 0.0, double = 0.0 );  
   void setWage( double );
   double getWage() const;
   void setHours( double );
   double getHours() const;
   virtual double earnings() const;
   virtual void print() const;
private:
   double wage;
   double hours;
};

#endif
//HourlyEmployee.cpp
#include <iostream>
#include "HourlyEmployee.h"
using namespace std;

HourlyEmployee::HourlyEmployee( const string &first, const string &last, 
   const string &ssn, int month, int day, int year, 
   double hourlyWage, double hoursWorked )
   : Employee( first, last, ssn, month, day, year )   
{
   setWage( hourlyWage );
   setHours(hoursWorked);
}

void HourlyEmployee::setWage( double hourlyWage ) 
{
   wage = ( hourlyWage < 0.0 ? 0.0 : hourlyWage ); 
}

double HourlyEmployee::getWage() const
{
   return wage;
}

void HourlyEmployee::setHours( double hoursWorked )
{ 
   hours = ( ( ( hoursWorked >= 0.0 ) &&
      ( hoursWorked <= hoursPerWeek ) ) ? hoursWorked : 0.0 );
}

double HourlyEmployee::getHours() const
{
   return hours;
}

double HourlyEmployee::earnings() const 
{ 
   if ( getHours() <= 40 )
      return getWage() * getHours();
   else               
      return 40 * getWage() + ( ( getHours() - 40 ) * getWage() * 1.5 );
}

void HourlyEmployee::print() const
{
   cout << "hourly employee: ";
   Employee::print();
   cout << "\nhourly wage: " << getWage() << 
      "; hours worked: " << getHours();
}
//BasePlusCommissionEmployee.h
#ifndef BASEPLUS_H
#define BASEPLUS_H

#include "CommissionEmployee.h"

class BasePlusCommissionEmployee : public CommissionEmployee
{
public:
    BasePlusCommissionEmployee(const string&, const string&,
        const string&, int, int, int, double = 0.0, double = 0.0,
        double = 0.0);
    void setBaseSalary(double);
    double getBaseSalary() const;
    virtual double earnings() const;
    virtual void print() const;
private:
    double baseSalary;
};

#endif
//BasePlusCommissionEmployee.cpp
#include <iostream>
#include "BasePlusCommissionEmployee.h"
using namespace std;

BasePlusCommissionEmployee::BasePlusCommissionEmployee( 
   const string &first, const string &last, const string &ssn, 
   int month, int day, int year, double sales, 
   double rate, double salary )
   : CommissionEmployee( first, last, ssn, month, day, year, sales, rate )  
{
   setBaseSalary( salary );
}

void BasePlusCommissionEmployee::setBaseSalary( double salary )
{ 
   baseSalary = ( ( salary < 0.0 ) ? 0.0 : salary ); 
}

double BasePlusCommissionEmployee::getBaseSalary() const
{ 
    return baseSalary; 
}

double BasePlusCommissionEmployee::earnings() const
{ 
    return getBaseSalary() + CommissionEmployee::earnings(); 
}

void BasePlusCommissionEmployee::print() const
{
   cout << "base-salaried ";
   CommissionEmployee::print();
   cout << "; base salary: " << getBaseSalary();
}
//main.cpp
#include <iostream>
#include <iomanip>
#include <vector>
#include <typeinfo>
#include <ctime>

#include "Employee.h"
#include "SalariedEmployee.h" 
#include "HourlyEmployee.h"
#include "CommissionEmployee.h" 
#include "BasePlusCommissionEmployee.h" 
using namespace std;

int determineMonth();

int main()
{
    cout << fixed << setprecision(2);
    vector < Employee* > employees(4);
    employees[0] = new SalariedEmployee(
        "John", "Smith", "111-11-1111", 6, 15, 1944, 800);
    employees[1] = new HourlyEmployee(
        "Karen", "Price", "222-22-2222", 12, 29, 1960, 16.75, 40);
    employees[2] = new CommissionEmployee(
        "Sue", "Jones", "333-33-3333", 9, 8, 1954, 10000, .06);
    employees[3] = new BasePlusCommissionEmployee(
        "Bob", "Lewis", "444-44-4444", 3, 2, 1965, 5000, .04, 300);
    int month = determineMonth();
    cout << "Employees processed polymorphically via dynamic binding:\n\n";
    for (size_t i = 0; i < employees.size(); i++)
    {
        employees[i]->print();
        cout << endl;
        BasePlusCommissionEmployee* derivedPtr =
            dynamic_cast <BasePlusCommissionEmployee*>
            (employees[i]);
        if (derivedPtr != 0)
        {
            double oldBaseSalary = derivedPtr->getBaseSalary();
            cout << "old base salary: $" << oldBaseSalary << endl;
            derivedPtr->setBaseSalary(1.10 * oldBaseSalary);
            cout << "new base salary with 10% increase is: $"
                << derivedPtr->getBaseSalary() << endl;
        }
        Date birthday = employees[i]->getBirthDate();
        if (birthday.getMonth() == month)
            cout << "HAPPY BIRTHDAY!\nearned $"
            << (employees[i]->earnings() + 100.0) << endl;
        else
            cout << "earned $" << employees[i]->earnings() << endl;
        cout << endl;
    }
    for (size_t j = 0; j < employees.size(); j++)
    {
        cout << "deleting object of "
            << typeid(*employees[j]).name() << endl;
        delete employees[j];
    }
}

int determineMonth()
{
    time_t currentTime;
    char monthString[3];
    time(&currentTime);
    strftime(monthString, 3, "%m", localtime(&currentTime));
    return atoi(monthString);
}

第十三章

13.7(输入十进制、八进制、十六进制的数值)

#include <iostream> 
#include <iomanip> 
#include <string>
using namespace std;

void show( const string message )
{
   int integer;
   cout << "\n" << message;
   cin >> integer;   
   cout << showbase << "As a decimal number "  << dec 
      << integer << "\nAs an octal number " << oct << integer
      << "\nAs a hexadecimal number " << hex << integer << endl;
}//showbase输出时显示所有数值的基数

int main()
{
   show( "Enter an integer: " );
   cin >> oct;
   show( "Enter an integer in octal format: " );
   cin >> hex;
   show( "Enter an integer in hexadecimal format: " );
}

13.8(打印指针值为整数)

#include <iostream> 
using namespace std;

int main()
{ 
    char s[] = "test";
    char* string =s;
    cout << "Value of string is: " << string << '\n'
        << "Value of static_cast<void *>( string ) is    : "
        << static_cast<void*>(string) << '\n'
        /*以下均为error
        << "Value of static_cast<char>(string) is      : "
        << static_cast<char>(string) << '\n'
        << "Value of static_cast<int>(string) is       : "
        << static_cast<int>(string) << '\n'
        << "Value of static_cast<long>(string) is      : "
        << static_cast<long>(string) << '\n'
        << "Value of static_cast<short>(string) is     : "
        << static_cast<short>(string) << '\n'
        << "Value of static_cast<unsigned>(string) is  : "
        << static_cast<unsigned>(string) */
        << endl;
}

13.9(根据域宽来打印)

#include <iostream> 
#include <iomanip> 
using namespace std;

int main()
{
    int x = 12345;
    double y = 1.2345;
    for (int loop = 0; loop <= 10; loop++)
        cout << x << "  printed in a field of size " << setw(2)
        << loop << " is " << setw(loop) << x << '\n' << y
        << " printed in a field of size " << setw(2)
        << loop << " is " << setw(loop) << y << '\n';
}

13.10(取整)

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double x = 100.453627;
    cout << fixed;
    for (int loop = 0; loop <= 5; loop++)
        cout << setprecision(loop) << "Rounded to " << loop
        << " digit(s) is " << x << endl;
}

13.11(一个字符串的长度)

#include <iostream> 
#include <iomanip> 
#include <string>
using namespace std;

int main()
{
	string input;
	int stringLength;
	cout << "Enter a string: ";
	cin >> input;
	stringLength = input.length();
	cout << "the length of the string is " << stringLength << endl;
	cout << setw(2 * stringLength) << input << endl;
}

13.12(将华氏温度转换为摄氏温度)

#include <iostream> 
#include <iomanip> 
using namespace std;

int main()
{
   double celsius;
   cout << setw( 20 ) << "Fahrenheit " << setw( 20 ) << "Celsius\n"
      << fixed << showpoint;
   for ( int fahrenheit = 0; fahrenheit <= 212; fahrenheit++ ) 
   {
       celsius = 5.0 / 9.0 * ( fahrenheit - 32 );
       cout << setw( 15 ) << noshowpos << fahrenheit << setw( 23 ) 
          << setprecision( 3 ) << showpos << celsius << '\n';
   }
}

13.14(用流提取运算符或者重载的流提取运算符来读电话号码)

//PhoneNumber.h 
#ifndef PHONENUMBER_H
#define PHONENUMBER_H

#include <iostream>
using namespace std;

class PhoneNumber 
{
   friend ostream& operator<<( ostream&, const PhoneNumber& );
   friend istream& operator>>( istream&, PhoneNumber& );
public:
   PhoneNumber();
private:
   char phone[ 15 ];
   char areaCode[ 4 ];
   char exchange[ 4 ];
   char line[ 5 ];
};

#endif
//PhoneNumber.cpp
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "PhoneNumber.h"
using namespace std;

PhoneNumber::PhoneNumber()
{
   phone[ 0 ] = '\0';
   areaCode[ 0 ] = '\0';
   exchange[ 0 ] = '\0';
   line[ 0 ] = '\0';
}

ostream& operator<<(ostream& output, const PhoneNumber& number)
{
    output << "(" << number.areaCode << ") " << number.exchange
        << "-" << number.line << '\n';
    return output;
}

istream& operator>>(istream& input, PhoneNumber& number)
{
    input.getline(number.phone, 15);
    if (strlen(number.phone) != 14)
        input.clear(ios::failbit);
    if (number.phone[0] != '(' || number.phone[4] != ')' ||
        number.phone[9] != '-')
        input.clear(ios::failbit);
    if (number.phone[1] == '0' || number.phone[6] == '0' ||
        number.phone[1] == '1' || number.phone[6] == '1')
        input.clear(ios::failbit);
    if (number.phone[2] != '0' && number.phone[2] != '1')
        input.clear(ios::failbit);
    if (!input.fail())
    {
        int loop;
        for (loop = 0; loop <= 2; loop++)
        {
            number.areaCode[loop] = number.phone[loop + 1];
            number.exchange[loop] = number.phone[loop + 6];
        }
        number.areaCode[loop] = number.exchange[loop] = '\0';
        for (loop = 0; loop <= 3; loop++)
            number.line[loop] = number.phone[loop + 10];
        number.line[loop] = '\0';
    }
    else
    {
        cerr << "Invalid phone number entered.\n";
        exit(1);
    }
    return input;
}
//main.cpp
#include <iostream>
#include "PhoneNumber.h"
using namespace std;

int main()
{
   PhoneNumber telephone;
   cout << "Enter a phone number in the form (123) 456-7890:\n";
   cin >> telephone;
   cout << "The phone number entered was:  " << telephone << endl;
   cout << "Now enter an invalid phone number:\n";
   cin >> telephone;
}

13.15(Piont类)

//Point.h
#ifndef POINT_H
#define POINT_H

#include <iostream>
using namespace std;

class Point 
{
   // overloaded input and output operators
   friend ostream &operator<<( ostream&, const Point& );
   friend istream &operator>>( istream&, Point& );

private:
   int xCoordinate;
   int yCoordinate;
};

#endif
//Point.cpp
#include <iostream>
#include "Point.h"
using namespace std;

ostream& operator<<(ostream& out, const Point& p)
{
    out << "(" << p.xCoordinate << ", " << p.yCoordinate << ")\n";
    return out;
}

istream& operator>>(istream& in, Point& p)
{
    if (in.peek() != '(')
        in.clear(ios::failbit);
    else
    {
        in.ignore();
        in >> p.xCoordinate;
        if (in.peek() != ',')
            in.clear(ios::failbit);
        else
        {
            in.ignore();
            if (in.peek() != ' ')
                in.clear(ios::failbit);
            else
            {
                in.ignore();
                in >> p.yCoordinate;
                if (in.peek() != ')')
                    in.clear(ios::failbit);
                else
                    in.ignore();
            }
        }
    }
    return in;
}
//main.cpp
#include <iostream>
#include "Point.h"
using namespace std;

int main()
{
    Point pt;
    cout << "Enter a point in the form (x, y):\n";
    cin >> pt;
    if (!cin.fail())
        cout << "Point entered was: " << pt << endl;
    else
        cout << "\nInvalid data\n";
}
//Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>
using namespace std;

class Complex
{
	friend ostream& operator<<(ostream&, const Complex&);
	friend istream& operator>>(istream&, Complex&);
public:
	Complex(void);
private:
	int real;
	int imaginary;
};

#endif
//Complex.cpp
#include <iostream> 
#include <iomanip> 
#include "Complex.h"
using namespace std;

Complex::Complex(void) :
    real(0),
    imaginary(0)
{
}

ostream& operator<<(ostream& output, const Complex& c)
{
    output << c.real << showpos << c.imaginary << "i\n" << showpos;
    return output;
}

istream& operator>>(istream& input, Complex& c)
{
    int number;
    int multiplier;
    char temp;
    input >> number;
    if (input.peek() == ' ')
    {
        c.real = number;
        input >> temp;
        multiplier = (temp == '+') ? 1 : -1;
        if (input.peek() != ' ')
            input.clear(ios::failbit);
        else
        {
            if (input.peek() == ' ')
            {
                input >> c.imaginary;
                c.imaginary *= multiplier;
                input >> temp;
                if (input.peek() != '\n')
                    input.clear(ios::failbit);
            }
            else
                input.clear(ios::failbit);
        }
    }
    else if (input.peek() == 'i')
    {
        input >> temp;
        if (input.peek() == '\n')
        {
            c.real = 0;
            c.imaginary = number;
        }
        else
            input.clear(ios::failbit);
    }
    else if (input.peek() == '\n')
    {
        c.real = number;
        c.imaginary = 0;
    }
    else
        input.clear(ios::failbit);
    return input;
}
//main.cpp
#include <iostream>
#include "Complex.h"
using namespace std;

int main()
{
   Complex complex;
   cout << "Input a complex number in the form A + Bi:\n";
   cin >> complex;
   if ( !cin.fail() )
      cout << "Complex number entered was:\n" << complex << endl;
   else
      cout << "Invalid Data Entered\n";
}

13.17(打印ASCII值列表)

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    cout << setw(7) << "Decimal" << setw(9) << "Octal " << setw(15)
        << "Hexadecimal " << setw(13) << "Character" << showbase << '\n';
    for (int loop = 33; loop <= 126; loop++)
        cout << setw(7) << dec << loop << setw(9) << oct << loop
        << setw(15) << hex << loop << setw(13)
        << static_cast<char>(loop) << endl;
}

空字符终止字符串

#include <iostream> 
using namespace std;

const int SIZE = 80;

int main()
{
	char array[SIZE];
	char array2[SIZE];
	char c;
	cout << "Enter a sentence to test getline() and get():\n";
	cin.getline(array, SIZE, '*');
	cout << array << '\n';
	cin >> c;
	cout << "The next character in the input is: " << c << '\n';
	cin.get(array2, SIZE, '*');
	cout << array2 << '\n';
	cin >> c;
	cout << "The next character in the input is: " << c << '\n';
}

第十四章

14.6(文件匹配)

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void printOutput( ofstream&, int, string, string, double );

int main()
{
    int masterAccount;
    int transactionAccount;
    double masterBalance;
    double transactionBalance;
    string masterFirstName;
    string masterLastName;
    ifstream inOldMaster("oldmast.dat");
    ifstream inTransaction("trans.dat");
    ofstream outNewMaster("newmast.dat");
    if (!inOldMaster)
    {
        cerr << "Unable to open oldmast.dat\n";
        exit(1);
    }
    if (!inTransaction)
    {
        cerr << "Unable to open trans.dat\n";
        exit(1);
    }
    if (!outNewMaster)
    {
        cerr << "Unable to open newmast.dat\n";
        exit(1);
    }
    cout << "Processing...\n";
    inTransaction >> transactionAccount >> transactionBalance;
    while (!inTransaction.eof())
    {
        inOldMaster >> masterAccount >> masterFirstName
            >> masterLastName >> masterBalance;
        while (masterAccount < transactionAccount && !inOldMaster.eof())
        {
            printOutput(outNewMaster, masterAccount, masterFirstName,
                masterLastName, masterBalance);
            inOldMaster >> masterAccount >> masterFirstName
                >> masterLastName >> masterBalance;
        }
        if (masterAccount > transactionAccount)
        {
            cout << "Unmatched transaction record for account "
                << transactionAccount << '\n';
            inTransaction >> transactionAccount >> transactionBalance;
        }
        if (masterAccount == transactionAccount)
        {
            masterBalance += transactionBalance;
            printOutput(outNewMaster, masterAccount, masterFirstName,
                masterLastName, masterBalance);
        }
        inTransaction >> transactionAccount >> transactionBalance;
    }
    while (!inOldMaster.eof())
    {
        inOldMaster >> masterAccount >> masterFirstName
            >> masterLastName >> masterBalance;
        printOutput(outNewMaster, masterAccount, masterFirstName,
            masterLastName, masterBalance);
    }
}

14.7(文件匹配测试数据)

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
    const int ITEMS = 4;
    const int accountNumbers[ITEMS] = { 100, 300, 500, 700 };
    const string names[ITEMS] =
    { "Alan Jones", "Mary Smith", "Sam Sharp", "Suzy Green" };
    const double balances[ITEMS] = { 348.17, 27.19, 0.00, -14.22 };
    const double transactionAmounts[ITEMS] =
    { 27.14, 62.11, 100.56, 82.17 };
    ofstream outOldMaster("oldMast.dat");
    ofstream outTransaction("trans.dat");
    if (!outOldMaster)
    {
        cerr << "Unable to open oldmast.dat\n";
        exit(1);
    }
    if (!outTransaction)
    {
        cerr << "Unable to open trans.dat\n";
        exit(1);
    }
    cout << fixed << showpoint << "Contents of \"oldmast.dat\":\n";
    outOldMaster << fixed << showpoint;
    for (int i = 0; i < ITEMS; ++i)
    {
        outOldMaster << accountNumbers[i] << ' ' << names[i] << ' '
            << setprecision(2) << balances[i] << '\n';
        cout << accountNumbers[i] << ' ' << names[i] << ' '
            << setprecision(2) << balances[i] << '\n';
    }
    cout << "\nContents of \"trans.dat\":\n";
    outTransaction << fixed << showpoint;
    for (int i = 0; i < ITEMS; ++i)
    {
        outTransaction << accountNumbers[i] << ' ' << setprecision(2)
            << transactionAmounts[i] << '\n';
        cout << accountNumbers[i] << ' ' << setprecision(2)
            << transactionAmounts[i] << '\n';
    }
}

14.9(增强文件匹配)

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;

void printOutput( ofstream &, int, string, string, double );

int main()
{
    int masterAccount;
    int transactionAccount;
    double masterBalance;
    double transactionBalance;
    string masterFirstName;
    string masterLastName;
    ifstream inOldmaster("oldmast.dat");
    ifstream inTransaction("trans.dat");
    ofstream outNewmaster("newmast.dat");
    if (!inOldmaster)
    {
        cerr << "Unable to open oldmast.dat\n";
        exit(1);
    }
    if (!inTransaction)
    {
        cerr << "Unable to open trans.dat\n";
        exit(1);
    }
    if (!outNewmaster)
    {
        cerr << "Unable to open newmast.dat\n";
        exit(1);
    }
    cout << "Processing....\n";
    inTransaction >> transactionAccount >> transactionBalance;
    while (!inTransaction.eof())
    {
        inOldmaster >> masterAccount >> masterFirstName >> masterLastName
            >> masterBalance;
        while (masterAccount < transactionAccount && !inOldmaster.eof())
        {
            printOutput(outNewmaster, masterAccount, masterFirstName,
                masterLastName, masterBalance);
            inOldmaster >> masterAccount >> masterFirstName >> masterLastName
                >> masterBalance;
        }
        if (masterAccount > transactionAccount)
        {
            cout << "Unmatched transaction record for account "
                << transactionAccount << '\n';
            inTransaction >> transactionAccount >> transactionBalance;
        }
        else if (masterAccount < transactionAccount)
        {
            cout << "Unmatched transaction record for account "
                << transactionAccount << '\n';
            inTransaction >> transactionAccount >> transactionBalance;
        }
        while (masterAccount == transactionAccount &&
            !inTransaction.eof())
        {
            masterBalance += transactionBalance;
            inTransaction >> transactionAccount >> transactionBalance;
        }
        printOutput(outNewmaster, masterAccount, masterFirstName,
            masterLastName, masterBalance);
    }
    while (!inOldmaster.eof())
    {
        inOldmaster >> masterAccount >> masterFirstName
            >> masterLastName >> masterBalance;
        printOutput(outNewmaster, masterAccount, masterFirstName,
            masterLastName, masterBalance);
    }
}

void printOutput(ofstream& oRef, int mAccount, string mfName,
    string mlName, double mBalance)
{
    cout << showpoint << fixed;
    oRef << showpoint << fixed;
    oRef << mAccount << ' ' << mfName << ' ' << mlName << ' '
        << setprecision(2) << mBalance << '\n';
    cout << mAccount << ' ' << mfName << ' ' << mlName << ' '
        << setprecision(2) << mBalance << '\n';
    cout << showpoint << fixed;
}

14.11(硬件清单)

//Tool.h
#ifndef TOOL_H
#define TOOL_H

#include <string>
using namespace std;

class Tool
{
public:
	static const int LENGTH = 30;
	Tool(int = -1, string = "", int = 0, double = 0.0);
	void setPartNumber(int);
	int getPartNumber() const;
	void setToolName(string);
	string getToolName() const;
	void setInStock(int);
	int getInStock() const;
	void setUnitPrice(double);
	double getUnitPrice() const;
private:
	int partNumber;
	char toolName[LENGTH];
	int inStock;
	double unitPrice;
};

#endif
//Tool.cpp
#include <string>
#include "Tool.h"
using namespace std;

Tool::Tool(int partNumberValue, string toolNameValue, int inStockValue,
	double unitPriceValue)
{
	setPartNumber(partNumberValue);
	setToolName(toolNameValue);
	setInStock(inStockValue);
	setUnitPrice(unitPriceValue);
}

void Tool::setPartNumber(int partNumberValue)
{
	partNumber = partNumberValue;
}

int Tool::getPartNumber() const
{
	return partNumber;
}

void Tool::setToolName(string toolNameString)
{
	int length = toolNameString.size();
	length = (length < LENGTH ? length : LENGTH - 1);
	toolNameString.copy(toolName, length);
	toolName[length] = '\0';
}

string Tool::getToolName() const
{
	return toolName;
}

void Tool::setInStock(int inStockValue)
{
	inStock = inStockValue;
}

int Tool::getInStock() const
{
	return inStock;
}

void Tool::setUnitPrice(double unitPriceValue)
{
	unitPrice = unitPriceValue;
}

double Tool::getUnitPrice() const
{
   return unitPrice;
}
//main.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cctype>
#include <cstdlib>
#include "Tool.h"
using namespace std;

void initializeFile( fstream & );
void inputData( fstream & );
void listTools( fstream & );
void updateRecord( fstream & );
void insertRecord( fstream & );
void deleteRecord( fstream & );
int instructions( void );

int main()
{
    int choice;
    char response;
    fstream file("hardware.dat", ios::in | ios::out);
    void (*f[])(fstream&) =
    { listTools, updateRecord, insertRecord, deleteRecord };
    if (!file)
    {
        cerr << "File could not be opened.\n";
        exit(1);
    }
    cout << "Should the file be initialized (Y or N): ";
    cin >> response;
    response = toupper(response);
    while ((response != 'Y') && (response != 'N'))
    {
        cout << "Invalid response. Enter Y or N: ";
        cin >> response;
        response = toupper(response);
    }
    if (response == 'Y')
    {
        initializeFile(file);
        inputData(file);
    }
    while ((choice = instructions()) != 5)
    {
        (*f[choice - 1])(file);
        file.clear();
    }
}

void initializeFile(fstream& fRef)
{
    Tool blankItem;
    for (int i = 0; i < 100; i++)
        fRef.write(
            reinterpret_cast<char*>(&blankItem), sizeof(Tool));
}

void inputData(fstream& fRef)
{
    Tool temp;
    int number;
    string name;
    double price;
    int stock;
    cout << "Enter the part number (0 - 99, -1 to end input): ";
    cin >> number;
    while (number != -1)
    {
        cout << "Enter the tool name: ";
        cin.ignore();
        getline(cin, name);
        temp.setToolName(name);
        temp.setPartNumber(number);
        cout << "Enter quantity and price: ";
        cin >> stock >> price;
        temp.setInStock(stock);
        temp.setUnitPrice(price);
        fRef.seekp(temp.getPartNumber() * sizeof(Tool));
        fRef.write(reinterpret_cast<char*>(&temp), sizeof(Tool));
        cout << "Enter the part number (0 - 99, -1 to end input): ";
        cin >> number;
    }
}

int instructions()
{
   int choice;
   cout << "\nEnter a choice:\n1  List all tools."
      << "\n2  Update record.\n3  Insert record."
      << "\n4  Delete record.\n5  End program.\n";
   do 
   {
      cout << "? ";
      cin >> choice;
   } while ( choice < 1 || choice > 5 );
   return choice;
}

void listTools(fstream& fRef)
{
    Tool temp;
    cout << setw(7) << "Record#" << "    " << left
        << setw(30) << "Tool name" << left
        << setw(13) << "Quantity" << left << setw(10) << "Cost" << endl;
    for (int count = 0; count < 100 && !fRef.eof(); count++)
    {
        fRef.seekg(count * sizeof(Tool));
        fRef.read(reinterpret_cast<char*>(&temp), sizeof(Tool));
        if (temp.getPartNumber() >= 0 && temp.getPartNumber() < 100)
        {
            cout << fixed << showpoint;
            cout << left << setw(7) << temp.getPartNumber() << "    "
                << left << setw(30) << temp.getToolName() << left
                << setw(13) << temp.getInStock() << setprecision(2)
                << left << setw(10) << temp.getUnitPrice() << '\n';
        }
    }
}

void updateRecord(fstream& fRef)
{
    Tool temp;
    int part;
    string name;
    int stock;
    double price;
    cout << "Enter the part number for update: ";
    cin >> part;
    fRef.seekg(part * sizeof(Tool));
    fRef.read(reinterpret_cast<char*>(&temp), sizeof(Tool));
    if (temp.getPartNumber() != -1)
    {
        cout << setw(7) << "Record#" << "    " << left
            << setw(30) << "Tool name" << left
            << setw(13) << "Quantity" << setw(10) << "Cost" << endl;
        cout << fixed << showpoint;
        cout << setw(7) << temp.getPartNumber() << "    "
            << left << setw(30) << temp.getToolName()
            << left << setw(13) << temp.getInStock()
            << setprecision(2) << setw(10) << temp.getUnitPrice() << '\n'
            << "Enter the tool name: ";
        cin.ignore();
        getline(cin, name);
        temp.setToolName(name);
        cout << "Enter quantity and price: ";
        cin >> stock >> price;
        temp.setInStock(stock);
        temp.setUnitPrice(price);
        fRef.seekp(temp.getPartNumber() * sizeof(Tool));
        fRef.write(reinterpret_cast<char*> (&temp), sizeof(Tool));
    }
    else
        cerr << "Cannot update. The record is empty.\n";
}

void insertRecord(fstream& fRef)
{
    Tool temp;
    int part;
    string name;
    int stock;
    double price;
    cout << "Enter the part number for insertion: ";
    cin >> part;
    fRef.seekg(part * sizeof(Tool));
    fRef.read(reinterpret_cast<char*> (&temp), sizeof(Tool));
    if (temp.getPartNumber() == -1)
    {
        temp.setPartNumber(part);
        cout << "Enter the tool name: ";
        cin.ignore();
        getline(cin, name);
        temp.setToolName(name);
        cout << "Enter quantity and price: ";
        cin >> stock >> price;
        temp.setInStock(stock);
        temp.setUnitPrice(price);
        fRef.seekp(temp.getPartNumber() * sizeof(Tool));
        fRef.write(reinterpret_cast<char*>(&temp), sizeof(Tool));
    }
    else
        cerr << "Cannot insert. The record contains information.\n";
}

void deleteRecord(fstream& fRef)
{
    Tool blankItem;
    Tool temp;
    int part;
    cout << "Enter the part number for deletion: ";
    cin >> part;
    fRef.seekg(part * sizeof(Tool));
    fRef.read(reinterpret_cast<char*>(&temp), sizeof(Tool));
    if (temp.getPartNumber() != -1)
    {
        fRef.seekp(part * sizeof(Tool));
        fRef.write(
            reinterpret_cast<char*>(&blankItem), sizeof(Tool));
        cout << "Record deleted.\n";
    }
    else
        cerr << "Cannot delete. The record is empty.\n";
}

14.12(电话号码数字生成器)

#include <iostream> 
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void wordGenerator( const int * const );

int main()
{
    int phoneNumber[7] = { 0 };
    cout << "Enter a phone number (digits 2 through 9) "
        << "in the form: xxx-xxxx\n";
    for (int v = 0; v < 7; )
    {
        int i = cin.get();
        if (i >= '2' && i <= '9')
            phoneNumber[v++] = i - '0';
    }
    wordGenerator(phoneNumber);
}

void wordGenerator( const int * const n )
{
   ofstream outFile( "phone.dat" );
   const string phoneLetters[ 10 ] = { "", "", "ABC", "DEF", "GHI",
      "JKL", "MNO", "PRS", "TUV", "WXY" };
   if ( !outFile ) 
   {
      cerr << "\"phone.dat\" could not be opened.\n";
      exit( 1 );
   }
   int count = 0;
   for ( int i1 = 0; i1 <= 2; i1++ )
   {
      for ( int i2 = 0; i2 <= 2; i2++ )
      {
         for ( int i3 = 0; i3 <= 2; i3++ )
         {
            for ( int i4 = 0; i4 <= 2; i4++ )
            {
               for ( int i5 = 0; i5 <= 2; i5++ )
               {
                  for ( int i6 = 0; i6 <= 2; i6++ )
                  {
                     for ( int i7 = 0; i7 <= 2; i7++ ) 
                     {
                        outFile << phoneLetters[ n[ 0 ] ][ i1 ]
                           << phoneLetters[ n[ 1 ] ][ i2 ]
                           << phoneLetters[ n[ 2 ] ][ i3 ]
                           << phoneLetters[ n[ 3 ] ][ i4 ]
                           << phoneLetters[ n[ 4 ] ][ i5 ]
                           << phoneLetters[ n[ 5 ] ][ i6 ]
                           << phoneLetters[ n[ 6 ] ][ i7 ] << ' ';
                        if ( ++count % 9 == 0 )
                           outFile << '\n';
                     }
                  }
               }
            }
         }
      }
   }
   outFile << "\nPhone number is ";
   for ( int i = 0; i < 7; i++ ) 
   {
      if ( i == 3 )
         outFile << '-';
      outFile << n[ i ];
   }
}

14.13(sizeof运算符)

#include <iostream> 
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
    ofstream outFile("datasize.dat");
    if (!outFile)
    {
        cerr << "Unable to open \"datasize.dat\".\n";
        exit(1);
    }
    outFile << "Data type" << setw(24) << "Size\nchar" << setw(21)
        << sizeof(char) << "\nunsigned char" << setw(12)
        << sizeof(unsigned char) << "\nshort int" << setw(16)
        << sizeof(short int) << "\nunsigned short int" << setw(7)
        << sizeof(unsigned short) << "\nint" << setw(22)
        << sizeof(int) << '\n';
    outFile << "unsigned int" << setw(13) << sizeof(unsigned)
        << "\nlong int" << setw(17) << sizeof(long)
        << "\nunsigned long int" << setw(8) << sizeof(unsigned long)
        << "\nfloat" << setw(20) << sizeof(float)
        << "\ndouble" << setw(19) << sizeof(double)
        << "\nlong double" << setw(14) << sizeof(long double) << endl;
}