欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案

程序员文章站 2024-03-11 12:07:43
...

第十一章 编程练习
1.修改程序清单11.15, 使之将一系列连续的随机漫步者位置写入文件中。对于每个位置,用步号进行标示。另外,让该程序将初始条件(目标距离和步长)以结果小结写入到该文件中。
头文件:

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
    class Vector
    {
    public:
        enum Mode {RECT, POL};
    // RECT for rectangular, POL for Polar modes
    private:
        double x;          // horizontal value
        double y;          // vertical value
        double mag;        // length of vector
        double ang;        // direction of vector in degrees
        Mode mode;         // RECT or POL
    // private methods for setting values
        void set_mag();
        void set_ang();
        void set_x();
        void set_y();
    public:
        Vector();
        Vector(double n1, double n2, Mode form = RECT);
        void reset(double n1, double n2, Mode form = RECT);
        ~Vector();
        double xval() const {return x;}       // report x value
        double yval() const {return y;}       // report y value
        double magval() const {return mag;}   // report magnitude
        double angval() const {return ang;}   // report angle
        void polar_mode();                    // set mode to POL
        void rect_mode();                     // set mode to RECT
    // operator overloading
        Vector operator+(const Vector & b) const;
        Vector operator-(const Vector & b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
    // friends
        friend Vector operator*(double n, const Vector & a);
        friend std::ostream & operator<<(std::ostream & os, const Vector & v);
    };
}   // end namespace VECTOR
#endif

类中成员函数使用方法解释文件:

// vect.cpp -- methods for the Vector class
#include <cmath>
#include "vector.h"   // includes <iostream>
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;
namespace VECTOR
{
    // compute degrees in one radian
    const double Rad_to_deg = 45.0 / atan(1.0);
    // should be about 57.2957795130823
    // private methods
    // calculates magnitude from x and y
    void Vector::set_mag()
    {
        mag = sqrt(x * x + y * y);
    }
    void Vector::set_ang()
    {
        if (x == 0.0 && y == 0.0)
            ang = 0.0;
        else
            ang = atan2(y, x);
    }
    // set x from polar coordinate
    void Vector::set_x()
    {
        x = mag * cos(ang);
    }
    // set y from polar coordinate
    void Vector::set_y()
    {
        y = mag * sin(ang);
    }
    // public methods
    Vector::Vector()             // default constructor
    {
        x = y = mag = ang = 0.0;
        mode = RECT;
    }
    // construct vector from rectangular coordinates if form is r
    // (the default) or else from polar coordinates if form is p
    Vector::Vector(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             set_mag();
             set_ang();
        }
        else if (form == POL)
        {
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x();
             set_y();
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = mag = ang = 0.0;
             mode = RECT;
        }
    }
    // reset vector from rectangular coordinates if form is
    // RECT (the default) or else from polar coordinates if
    // form is POL
    void Vector:: reset(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             set_mag();
             set_ang();
        }
        else if (form == POL)
        {
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x();
             set_y();
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = mag = ang = 0.0;
             mode = RECT;
        }
    }
    Vector::~Vector()    // destructor
    {
    }
    void Vector::polar_mode()    // set to polar mode
    {
        mode = POL;
    }
    void Vector::rect_mode()     // set to rectangular mode
    {
        mode = RECT;
    }
    // operator overloading
    // add two Vectors
    Vector Vector::operator+(const Vector & b) const
    {
        return Vector(x + b.x, y + b.y);
    }
    // subtract Vector b from a
    Vector Vector::operator-(const Vector & b) const
    {
        return Vector(x - b.x, y - b.y);
    }
    // reverse sign of Vector
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }
    // multiply vector by n
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }
    // friend methods
    // multiply n by Vector a
    Vector operator*(double n, const Vector & a)
    {
        return a * n;
    }
    // display rectangular coordinates if mode is RECT,
    // else display polar coordinates if mode is POL
    std::ostream & operator<<(std::ostream & os, const Vector & v)
    {
  if (v.mode == Vector::RECT)
             os << "(x,y) = (" << v.x << ", " << v.y << ")";
        else if (v.mode == Vector::POL)
        {
             os << "(m,a) = (" << v.mag << ", "
                 << v.ang * Rad_to_deg << ")";
        }
        else
             os << "Vector object mode is invalid";
        return os; 
    }
}  // end namespace VECTOR

对编程练习11.15的修改:

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include<fstream>
#include <cstdlib>      // rand(), srand() prototypes
#include <ctime>        // time() prototype
#include "vector.h"
int main()
{
    using namespace std;
    using VECTOR::Vector;
 ofstream fout;
 fout.open("thewalk.txt");
    srand(time(0));     // seed random-number generator
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;
    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
  cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
  fout<<"Target Distance: "<<target<<" , "<<"Step Size: "<<dstep<<endl;
        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
   fout<<steps<<" : "<<result<<endl;
            steps++;
        }
        fout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        fout << result << endl;
  cout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        cout << result << endl;
        result.polar_mode();
        fout << " or\n" << result << endl;
        fout << "Average outward distance per step = "
            << result.magval()/steps << endl;
  cout << " or\n" << result << endl;
        cout << "Average outward distance per step = "
            << result.magval()/steps << endl;
        steps = 0;
        result.reset(0.0, 0.0);
        cout << "Enter target distance (q to quit): ";
    }
    cout << "Bye!\n";
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}

程序运行结果:

C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案
2.对Vector类的头文件(程序清单11.13) 和实现文件(程序清单11.14 进行修改),使其不再存储矢量的长度和角度,而是在magval()和angval()被调用时计算它们应保留公有接口不变(公有方法及参数不变),但对私有部分(包括一些私有方法)和方法实现进行修改。然后,使用程序清单11.15 对修改后的版本进行测试,结果应该与以前相同,因为Vector类的公有接口与原来相同。
头文件: vect.h

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
    class Vector
    {
    public:
        enum Mode {RECT, POL};
    // RECT for rectangular, POL for Polar modes
    private:
        double x;          // horizontal value
        double y;          // vertical value
  Mode mode;
        void set_x(double mag,double ang);
        void set_y(double mag,double ang);
    public:
        Vector();
        Vector(double n1, double n2, Mode form = RECT);
        void reset(double n1, double n2, Mode form = RECT);
        ~Vector();
        double xval() const {return x;}       // report x value
        double yval() const {return y;}       // report y value
        double magval() const ;   // report magnitude
        double angval() const; // report angle
        void polar_mode();                    // set mode to POL
        void rect_mode();                     // set mode to RECT
    // operator overloading
        Vector operator+(const Vector & b) const;
        Vector operator-(const Vector & b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
    // friends
        friend Vector operator*(double n, const Vector & a);
        friend std::ostream & operator<<(std::ostream & os, const Vector & v);
    };
}   // end namespace VECTOR
#endif

头文件中的函数成员解释文件: vect.cpp

// vect.cpp -- methods for the Vector class
#include <cmath>
#include "alter_vector.h"   // includes <iostream>
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;
namespace VECTOR
{
    // compute degrees in one radian
    const double Rad_to_deg = 45.0 / atan(1.0);
    // should be about 57.2957795130823
    // private methods
 // set x from polar coordinate
 double Vector::magval()const
 {
  return sqrt(x * x + y * y);
 }
 double Vector::angval()const
 {
  if (x ==0.0 & y ==0)
   return 0.0;
  else
   return atan2(y,x);
 }
 void Vector::set_x(double mag,double ang)
    {
        x = mag * cos(ang);
    }
    // set y from polar coordinate
    void Vector::set_y(double mag,double ang)
    {
        y = mag * sin(ang);
    }
    // public methods
    Vector::Vector()             // default constructor
    {
        x = y = 0.0;
        mode = RECT;
    }
    // construct vector from rectangular coordinates if form is r
    // (the default) or else from polar coordinates if form is p
    Vector::Vector(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
        }
        else if (form == POL)
        {  
             set_x(n1,n2 / Rad_to_deg);
             set_y(n1,n2 / Rad_to_deg);
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = 0.0;
             mode = RECT;
        }
    }
    // reset vector from rectangular coordinates if form is
    // RECT (the default) or else from polar coordinates if
    // form is POL
    void Vector:: reset(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
        }
        else if (form == POL)
        {
             set_x(n1,n2 / Rad_to_deg);
             set_y(n1,n2 / Rad_to_deg);
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y =  0.0;
             mode = RECT;
        }
    }
    Vector::~Vector()    // destructor
    {
    }
    void Vector::polar_mode()    // set to polar mode
    {
        mode = POL;
    }
    void Vector::rect_mode()     // set to rectangular mode
    {
        mode = RECT;
    }
    // operator overloading
    // add two Vectors
    Vector Vector::operator+(const Vector & b) const
    {
        return Vector(x + b.x, y + b.y);
    }
    // subtract Vector b from a
    Vector Vector::operator-(const Vector & b) const
    {
        return Vector(x - b.x, y - b.y);
    }
    // reverse sign of Vector
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }
    // multiply vector by n
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }
    // friend methods
    // multiply n by Vector a
    Vector operator*(double n, const Vector & a)
    {
        return a * n;
    }
    // display rectangular coordinates if mode is RECT,
    // else display polar coordinates if mode is POL
    std::ostream & operator<<(std::ostream & os, const Vector & v)
    {
  if (v.mode == Vector::RECT)
             os << "(x,y) = (" << v.x << ", " << v.y << ")";
        else if (v.mode == Vector::POL)
        {
   os << "(m,a) = (" << v.magval() << ", "
    << v.angval() * Rad_to_deg << ")";
        }
        else
             os << "Vector object mode is invalid";
        return os; 
    }
}  // end namespace VECTOR

测试文件:

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include<fstream>
#include <cstdlib>      // rand(), srand() prototypes
#include <ctime>        // time() prototype
#include "alter_vector.h"
int main()
{
    using namespace std;
    using VECTOR::Vector;
    srand(time(0));     // seed random-number generator
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;
    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
        ofstream fout;
  fout.open("thewalk.txt");
  fout << "Enter step length: ";
  cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
        }
        fout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        fout << result << endl;
  cout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        cout << result << endl;
        result.polar_mode();
        fout << " or\n" << result << endl;
        fout << "Average outward distance per step = "
            << result.magval()/steps << endl;
  cout << " or\n" << result << endl;
        cout << "Average outward distance per step = "
            << result.magval()/steps << endl;
        steps = 0;
        result.reset(0.0, 0.0);
        cout << "Enter target distance (q to quit): ";
    }
    cout << "Bye!\n";
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}

运行结果:
C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案
3.修改程序清单11.15 ,使之报告N次测试中最高、最低和平均步数(其中N是用户输入的整数),而不是报告每次的结果。

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>      // rand(), srand() prototypes
#include <ctime>        // time() prototype
#include "alter_vector.h"
int main()
{
    using namespace std;
    using VECTOR::Vector;
    srand(time(0));     // seed random-number generator
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;
 unsigned long maxstep;
 unsigned long minstep;
 unsigned long sumsteps = 0;
 double averagestep;
 int i=0;
    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
  cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
        }
  cout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        if (i==0)
  {
   maxstep = steps;
   minstep = steps;
  }
  ++i;
  if(maxstep<steps)
   maxstep=steps;
  if (minstep>steps)
   minstep=steps;
  sumsteps +=steps;
  averagestep=sumsteps/i;
  cout<<"The maxstep is "<<maxstep<<endl;
  cout<<"The minstep is "<<minstep<<endl;
  cout<<"The averagestep is "<<averagestep<<endl;
        steps = 0;
        result.reset(0.0, 0.0);
        cout << "Enter target distance (q to quit): ";
    }
    cout << "Bye!\n";
    return 0; 
}

运行结果:
C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案
4.重新编写最后的Time类示例(程序清单11.10、 程序清单11.11 和程序清单11.12), 使友元函数来实现所有的重载运算符。
程序清单11.10修改:

// mytime.h -- Time class with friends
#ifndef MYTIME3_H_
#define MYTIME3_H_
#include <iostream>
class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m = 0);
    void AddMin(int m);
    void AddHr(int h);
    void Reset(int h = 0, int m = 0);
 friend Time operator+(const Time & m, const Time & t);
 friend Time operator-(const Time & m, const Time & t);
 friend Time operator*(const Time & m, double n);
    friend Time operator*(double m, const Time & t)
        { return t * m; }   // inline definition
    friend std::ostream & operator<<(std::ostream & os, const Time & t);
};
#endif

程序清单11.11修改:

// mytime.cpp  -- implementing Time methods
#include "mytime.h"
Time::Time()
{
    hours = minutes = 0;
}
Time::Time(int h, int m )
{
    hours = h;
    minutes = m;
}
void Time::AddMin(int m)
{
    minutes += m;
    hours += minutes / 60;
    minutes %= 60;
}
void Time::AddHr(int h)
{
    hours += h;
}
void Time::Reset(int h, int m)
{
    hours = h;
    minutes = m;
}
Time operator+(const Time & m, const Time & t)
{
 Time sum;
 sum.minutes=m.minutes+t.minutes;
 sum.hours=m.hours+t.hours+sum.minutes/60;
 sum.minutes %=60;
 return sum;
}
Time operator-(const Time & m, const Time & t)
{
 Time diff;
 int tot1, tot2;
 tot1 = t.minutes+ 60*t.hours;
 tot2 = m.minutes+60*m.hours;
 diff.minutes=(tot2-tot1)%60;
 diff.hours=(tot2-tot1)/60;
 return diff;
}
Time operator*(const Time & m, double n)
{
 Time result;
 long totalminutes = m.hours * n * 60 +m.minutes * n;
    result.hours = totalminutes / 60;
    result.minutes = totalminutes % 60;
    return result;
}
std::ostream & operator<<(std::ostream & os, const Time & t)
{
    os << t.hours << " hours, " << t.minutes << " minutes";
    return os; 
}

程序清单11.12修改:

//usetime.cpp -- using the fourth draft of the Time class
// compile usetime.cpp and mytime.cpp together
#include <iostream>
#include "mytime.h"
int main()
{
    using std::cout;
    using std::endl;
    Time aida(3, 35);
    Time tosca(2, 48);
    Time temp;
    cout << "Aida and Tosca:\n";
    cout << aida<<"; " << tosca << endl;
    temp = aida + tosca;     // operator+()
    cout << "Aida + Tosca: " << temp << endl;
    temp = aida* 1.17;  // member operator*()
    cout << "Aida * 1.17: " << temp << endl;
    cout << "10.0 * Tosca: " << 10.0 * tosca << endl;
 std::cin.get();
    return 0; 
}

运行结果:
C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案
5.重新编写Stonewt类(程序清单11.16 和程序清单11.17 ),使它有一个状态成员,由该成员控制对象应转换为英石格式、整数磅格式(翻译的不合适,应该是磅数格式)还是浮点磅格式(多少stone, 多少pounds)。重载<<运算符,使它来替换show_stn()和show_lbs()方法。 重载加法、减法和乘法运算符,以便可以对Stonewt进行加、减、乘运算。编写一个使用所有类方法和友元的小程序,来测试这个类。
程序清单11.16修改:

// stonewt.h -- definition for the Stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
 enum Mode{STONE,POUND,FLOAT};
 Mode model;
 enum {Lbs_per_stn = 14};      // pounds per stone
    //浮点格式
 int stone;                    // whole stones
    double pds_left;              // fractional pounds
    //整数磅
 double pounds;                // entire weight in pounds
public:
    Stonewt(double lbs);          // constructor for double pounds
    Stonewt(int stn, double lbs); // constructor for stone, lbs
    Stonewt();                    // default constructor
    ~Stonewt();
 //重载加法、减法和乘法运算符
 Stonewt operator+(const Stonewt & s) const;
 Stonewt operator-(const Stonewt & s) const;
 Stonewt operator*(double n) const;
 void set_model_STONE();
 void set_model_POUND();
 void set_model_FLOAT();
    friend Stonewt operator*(double n ,const Stonewt & s)
 {
  return s * n;
 }
 friend std::ostream&
  operator<<(std::ostream & os,const Stonewt & s);
};
#endif

程序清单11.17修改:

// stonewt.cpp -- Stonewt methods
#include <iostream>
using std::cout;
#include "Stonewt.h"
// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
    stone = int (lbs) / Lbs_per_stn;    // integer division
    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
    pounds = lbs;
 model = POUND;
}
// construct Stonewt object from stone, double values
Stonewt::Stonewt(int stn, double lbs)
{
    stone = stn;
    pds_left = lbs;
    pounds =  stn * Lbs_per_stn +lbs;
 model = FLOAT;
}
Stonewt::Stonewt()          // default constructor, wt = 0
{
    stone = pounds = pds_left = 0;
 model = STONE;
}
Stonewt::~Stonewt()         // destructor
{
}
void Stonewt::set_model_STONE()
{
 model = STONE;
}
void Stonewt::set_model_POUND()
{
 model = POUND;
}
void Stonewt::set_model_FLOAT()
{
 model = FLOAT;
}
Stonewt Stonewt::operator+(const Stonewt & s) const
{
 Stonewt temp;
 temp.pounds=pounds+s.pounds;
 temp.stone = temp.pounds / Lbs_per_stn;
 temp.pds_left=int(temp.pounds)%Lbs_per_stn + temp.pounds - int(temp.pounds);
 return temp;
}
Stonewt Stonewt::operator-(const Stonewt & s) const
{
 Stonewt temp;
 temp.pounds=pounds-s.pounds;
 temp.stone = temp.pounds / Lbs_per_stn;
 temp.pds_left=int(temp.pounds)%Lbs_per_stn + temp.pounds - int(temp.pounds);
 return temp;
}
Stonewt Stonewt::operator*(double n) const
{
 Stonewt temp;
 temp.pounds=pounds*n;
 temp.stone = temp.pounds / Lbs_per_stn;
 temp.pds_left=int(temp.pounds)%Lbs_per_stn + temp.pounds - int(temp.pounds);
 return temp;
}
std::ostream & operator<<(std::ostream & os,const Stonewt & s)
{
 if (s.model==Stonewt::STONE)
 {
  double stone = s.stone + s.pds_left / Stonewt::Lbs_per_stn;
  os<<stone<<" stones\n";
 }
 else if (s.model==Stonewt::POUND)
  os<<s.pounds<<" pounds\n";
 else
  os<<s.stone<<" stones, "<<s.pds_left<<" pounds\n";
 return os;
}

程序清单11.18修改:

// stone.cpp -- user-defined conversions
// compile with stonewt.cpp
#include <iostream>
using std::cout;
#include "stonewt.h"
void display(const Stonewt & st, int n);
int main()
{
    Stonewt incognito = 275; // uses constructor to initialize
    Stonewt wolfe(285.7);    // same as Stonewt wolfe = 285.7;
    Stonewt taft(21, 8);
    cout << "The incognito = 275 weighed ";
 incognito.set_model_POUND();
 cout<<incognito;
 incognito.set_model_STONE();
 cout<<incognito;
 incognito.set_model_FLOAT();
 cout<<incognito;
 cout << "The wolfe(285.7) weighed ";
 wolfe.set_model_POUND();
 cout<<wolfe;
 wolfe.set_model_STONE();
 cout<<wolfe;
 wolfe.set_model_FLOAT();
 cout<<wolfe;
 cout << "The taft(21, 8) weighed ";
 taft.set_model_POUND();
 cout<<taft;
 taft.set_model_STONE();
 cout<<taft;
 taft.set_model_FLOAT();
 cout<<taft;
 Stonewt sum=wolfe+taft;
 Stonewt diff=wolfe-taft;
 Stonewt product1=taft*2;
 Stonewt product2=2*taft;
 cout<<"SUM : "<<sum<<std::endl;
 cout<<"DIFF : "<<diff<<std::endl;
 cout<<"PRODUCT1 : "<<product1<<std::endl;
 cout<<"PRODUCT2 : "<<product2<<std::endl;
    std::cin.get();
    return 0;
}

运行结果:
C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案
6.重新编写Stonewt类(程序清单11.16 和程序清单11.17 ),重载全部6个关系运算符。
运算符对pounds成员进行比较,并返回一个bool值。编写一个程序,它声明一个包含6个Stonewt对象的数组,并在数组声明中初始化前3个对象。然后使用循环来读取用于设置剩余3个数组元素的值。接着报告最小的元素、最大的元素以及大于等于11英石的元素的数量(最简单的方法是创建一个Stonewt对象,并将其初始化为11英石,然后将其同其他对象进行比较)。
程序清单11.16修改:

// stonewt.h -- definition for the Stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
    enum {Lbs_per_stn = 14};      // pounds per stone
    int stone;                    // whole stones
    double pds_left;              // fractional pounds
    double pounds;                // entire weight in pounds
public:
    Stonewt(double lbs);          // constructor for double pounds
    Stonewt(int stn, double lbs); // constructor for stone, lbs
    Stonewt();                    // default constructor
    ~Stonewt();
 bool operator<(const Stonewt & s);
 bool operator<=(const Stonewt & s);
 bool operator>(const Stonewt & s);
 bool operator>=(const Stonewt & s);
 bool operator==(const Stonewt & s);
 bool operator!=(const Stonewt & s);
    void show_lbs() const;        // show weight in pounds format
    void show_stn() const;        // show weight in stone format
};
#endif

程序清单11.17修改:

// stonewt.cpp -- Stonewt methods
#include <iostream>
using std::cout;
#include "alter_Stonewt.h"
// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
    stone = int (lbs) / Lbs_per_stn;    // integer division
    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
    pounds = lbs;
}
// construct Stonewt object from stone, double values
Stonewt::Stonewt(int stn, double lbs)
{
    stone = stn;
    pds_left = lbs;
    pounds =  stn * Lbs_per_stn +lbs;
}
Stonewt::Stonewt()          // default constructor, wt = 0
{
    stone = pounds = pds_left = 0;
}
Stonewt::~Stonewt()         // destructor
{
}
bool Stonewt:: operator<(const Stonewt & s)
{
 if(pounds<s.pounds)
  return true;
 else
  return false;
}
bool Stonewt:: operator<=(const Stonewt & s)
{
 if(pounds<=s.pounds)
  return true;
 else
  return false;
}
bool Stonewt:: operator>(const Stonewt & s)
{
 if(pounds>s.pounds)
  return true;
 else
  return false;
}
bool Stonewt:: operator>=(const Stonewt & s)
{
 if(pounds>=s.pounds)
  return true;
 else
  return false;
}
bool Stonewt:: operator==(const Stonewt & s)
{
 if(pounds==s.pounds)
  return true;
 else
  return false;
}
bool Stonewt:: operator!=(const Stonewt & s)
{
 if(pounds!=s.pounds)
  return true;
 else
  return false;
}
// show weight in stones
void Stonewt::show_stn() const
{
    cout << stone << " stone, " << pds_left << " pounds\n";
}
// show weight in pounds
void Stonewt::show_lbs() const
{
    cout << pounds << " pounds\n";
}

程序清单11.18

// stone.cpp -- user-defined conversions
// compile with stonewt.cpp
#include <iostream>
using namespace std;
#include "alter_Stonewt.h"
int main()
{
    Stonewt array[6] = {275,Stonewt(285.7),Stonewt(21,8)};
 double input;
 Stonewt comparison_value = Stonewt(11,0);
 Stonewt max=array[0];
 Stonewt min=array[0];
 int sum=0;
 for (int i=3;i<6;i++)
 {
  cout<<"Enter the "<<i+1<<" pounds: ";
  cin>>input;
  array[i]=Stonewt(input);
  cin.get();
 }
 for (int i=1;i<6;i++)
 {
  if (max<array[i])
   max=array[i];
  if (min>array[i])
   min=array[i];
  if(array[i]>=comparison_value)
   sum++;
 }
 cout<<"MAX:\n";
 max.show_lbs();
 max.show_stn();
 cout<<"\nMIN:\n";
 min.show_lbs();
 min.show_stn();
 cout<<endl<<"There are "<<sum<<" exceed 11 stone.\n";
    cin.get();
    return 0;
}

运行结果:
C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案
7.操作复数的算术运算。
头文件://–complex.h —A class that defines basic functions of plurals

//--complex.h ---A class that defines basic functions of plurals
#ifndef COMPLEX_H_
#define COMPLEX_H_
class complex0
{
private:
 double realpart;
 double imagpart;
public:
 complex0(double realnumber=0,double imagnumber=0);
 ~complex0();
 friend complex0 operator+(const complex0 & m,const complex0 & s);
 friend complex0 operator-(const complex0 & m,const complex0 & s);
 friend complex0 operator*(const complex0 & m,const complex0 & s);
 friend complex0 operator*(double x,const complex0 & s);
 friend complex0 operator~(const complex0 & s);
 friend std::istream & operator>>(std::istream & is, complex0 & s);
 friend std::ostream & operator<<(std::ostream & os ,const complex0 & s);
};
#endif

方法文件://complex.cpp—method definitions for member functions

//complex.cpp---method definitions for member functions
#include<iostream>
#include"complex0.h"
using namespace std;
complex0::complex0(double realnumber,double imagnumber)
{
 realpart=realnumber;
 imagpart=imagnumber;
}
complex0::~complex0()
{
 cout<<"this is a destructor...\n";
}
complex0 operator+(const complex0 & m,const complex0 & s)
{
 complex0 temp;
 temp.realpart=m.realpart+s.realpart;
 temp.imagpart=m.imagpart+s.imagpart;
 return temp;
}
complex0 operator-(const complex0 & m,const complex0 & s)
{
 complex0 temp;
 temp.realpart=m.realpart-s.realpart;
 temp.imagpart=m.imagpart-s.imagpart;
 return temp;
}
complex0 operator*(const complex0 & m,const complex0 & s)
{
 complex0 temp;
 temp.realpart=m.realpart*s.realpart-m.imagpart*s.imagpart;
 temp.imagpart=m.realpart*s.imagpart+m.imagpart*s.realpart;
 return temp;
}
complex0 operator*(double x,const complex0 & s)
{
 complex0 temp;
 temp.realpart=x*s.realpart;
 temp.imagpart=x*s.imagpart;
 return temp;
}
complex0 operator~(const complex0 & s)
{
 complex0 temp;
 temp.realpart=s.realpart;
 temp.imagpart=-1*s.imagpart;
 return temp;
}
std::istream & operator>>(std::istream & is, complex0 & s)
{
 std::cout<<"realpart: ";
 is>>s.realpart;
 if(!is)
  return is;
 std::cout<<"imagpart: ";
 is>>s.imagpart;
 return is;
}
std::ostream & operator<<(std::ostream & os ,const complex0 & s)
{
 os<<"("<<s.realpart<<" , "<<s.imagpart<<"i)";
 return os;
}

测试文件://usecomplex.cpp–exercises using plural classes

//usecomplex.cpp--exercises using plural classes
#include<iostream>
using namespace std;
#include"complex0.h"
int main()
{
 complex0 a(3.0,4.0);
 complex0 c;
 cout<<"Enter a complex number (q to quit):\n";
 while (cin>>c)
 {
  cout<<"c is "<<c<<"\n";
  cout<<"complex conjugate is "<<~c<<'\n';
  cout<<"a is "<<a<<"\n";
  cout<<"a+c is "<<a+c<<"\n";
  cout<<"a-c is "<<a-c<<"\n";
  cout<<"a*c is "<<a*c<<"\n";
  cout<<"2*c is "<<2*c<<"\n";
  cout<<"Enter a complex number (q to quit):\n";
 }
 cout<<"Done!\n";
 cin.get();
 system("pause");
 return 0;
}

运行结果:
C++ Primer Plus (第6版) 中文版 第十一章 使用类 编程练习答案