【C++】C++PrimerPlus(第6版)中文版 第11章 使用类 编程练习 参考答案

自己编写的参考答案,在VS2019中都可以编译通过,不是标准答案,也不是最优答案,仅供参考

1.修改程序清单11.15,使之将一系列连续的随机漫步者位置写入到文件中。对于每个位置,用步号进行标志。另外,让该程序将初始条件(目标距离和步长)以及结果小结写入到该文件中。该文件的内容与下面类似:
Target Distance : 100, Step Size : 20
0 : (x, y) = (0, 0)
1 : (x, y) = (-11.4715, 16.383)
2 : (x, y) = (-868807, -3.42232)
26 : (x, y) = (42.2919, -78.2594)
27 : (x, y) = (58.6749, -89.7309)
After 27 steps, the subject has the following location :
(x, y) = (58.6749, -89.7309)
or
(m, a) = (107.212, -56.8194)
Average outward distance per step = 3.97081
.h:
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
    class Vector
    {
    public:
        enum Mode { RECT, POL };
    private:
        double x;
        double y;
        double mag;
        double ang;
        Mode mode;
        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; } 
        double yval() const { return y; }
        double magval() const { return mag; }
        double angval() const { return ang; }
        void polar_mode();
        void rect_mode();
        Vector operator+(const Vector& b) const;
        Vector operator-(const Vector& b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
        friend Vector operator*(double n, const Vector& a);
        friend std::ostream& operator<<(std::ostream& os, const Vector& v);
    };
}
#endif
.cpp:
#include <cmath>
#include "Topic1.h"
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;
namespace VECTOR
{
    const double Rad_to_deg = 45.0 / atan(1.0);
    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);
    }
    void Vector::set_x()
    {
        x = mag * cos(ang);
    }
    void Vector::set_y()
    {
        y = mag * sin(ang);
    }
    Vector::Vector()
    {
        x = y = mag = ang = 0.0;
        mode = RECT;
    }
    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;
        }
    }
    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()
    {
    }
    void Vector::polar_mode()
    {
        mode = POL;
    }
    void Vector::rect_mode()
    {
        mode = RECT;
    }
    Vector Vector::operator+(const Vector& b) const
    {
        return Vector(x + b.x, y + b.y);
    }
    Vector Vector::operator-(const Vector& b) const
    {
        return Vector(x - b.x, y - b.y);
    }
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }
    Vector operator*(double n, const Vector& a)
    {
        return a * n;
    }
    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;
    }
}
main():
#include<iostream>
#include<cstdlib>
#include<ctime>
#include <fstream>
#include "Topic1.h"
using namespace std;
int main()
{
 using VECTOR::Vector;
 srand(time(0));
 double direction;
 Vector step;
 Vector result(0.0, 0.0);
 unsigned long steps = 0;
 double target;
 double dstep;
 ofstream fout;
 fout.open("topic01.txt");
 cout << "Enter target distance (q to quit): ";
 while (cin >> target)
 {
  cout << "Enetr step length: ";
  if (!(cin >> dstep))
  {
   break;
  }
  else
  {
   fout <<"Target Distance : "<<target<<", Step Size : "<< dstep<<endl;
  }
  int i = 0;
  while (result.magval() < target)
  {
   direction = rand() % 360;
   step.reset(dstep, direction, Vector::POL);
   result = result + step;
   steps++;
   fout << i << " : (x, y) = (" << result.xval() << ", " << result.yval() << ")" << endl;
   i++;
  }
  fout << "After " << steps << " steps, the subject has the following location:\n";
  fout << result << endl;
  result.polar_mode();
  fout << " or\n" << result << endl;
  fout << "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";
 cin.clear();
 while (cin.get() != '\n')
  continue;
 return 0;
}
2.对Vector类的头文件(程序清单11.13)和实现文件(程序清单11.14)进行修改,使其不再存储矢量的长度和角度,而是在magval()和angval()被调用时计算它们。应保留公有接口不变(公有方法及其参数不变),但对私有部分(包括一些私有方法)和方法实现进行修改。然后,使用程序清单11.15对修改后的版本进行测试,结果应该与以前相同,因为Vector类的公有接口与原来相同。
.h:
#ifndef VECTOR_H_
#define VECTOR_H_
#include <cmath>
#include <iostream>
namespace VECTOR02
{
    class Vector
    {
    public:
        enum Mode { RECT, POL };
    private:
        double x;
        double y;
        Mode mode;
        double set_mag();
        double set_ang();
        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; } 
        double yval() const { return y; }
        double magval() const
        {  
            double mag;
            mag = sqrt(x * x + y * y);
            return mag;
        }
        double angval() const
        {
            double ang;
            if (x == 0.0 && y == 0.0)
                ang = 0.0;
            else
                ang = atan2(y, x);
            return ang;
        }
        void polar_mode();
        void rect_mode();
        Vector operator+(const Vector& b) const;
        Vector operator-(const Vector& b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
        friend Vector operator*(double n, const Vector& a);
        friend std::ostream& operator<<(std::ostream& os, const Vector& v);
    };
}
#endif
.cpp:
#include <cmath>
#include "Topic2.h"
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;
namespace VECTOR02
{
    const double Rad_to_deg = 45.0 / atan(1.0);
    double Vector::set_mag()
    {
        double mag;
        mag = sqrt(x * x + y * y);
        return mag;
    }
    double Vector::set_ang()
    {
        double ang;
        if (x == 0.0 && y == 0.0)
            ang = 0.0;
        else
            ang = atan2(y, x);
        return ang;
    }
    void Vector::set_x(double mag, double ang)
    {
        x = mag * cos(ang);
    }
    void Vector::set_y(double mag, double ang)
    {
        y = mag * sin(ang);
    }
    Vector::Vector()
    {
        x = y = 0.0;
        mode = RECT;
    }
    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)
        {
            double mag, ang;
            mag = n1;
            ang = n2 / Rad_to_deg;
            set_x(mag, ang);
            set_y(mag, ang);
        }
        else
        {
            cout << "Incorrect 3rd argument to Vector() -- ";
            cout << "vector set to 0\n";
            x = y = 0.0;
            mode = RECT;
        }
    }
    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)
        {
            double mag, ang;
            mag = n1;
            ang = n2 / Rad_to_deg;
            set_x(mag, ang);
            set_y(mag, ang);
        }
        else
        {
            cout << "Incorrect 3rd argument to Vector() -- ";
            cout << "vector set to 0\n";
            x = y = 0.0;
            mode = RECT;
        }
    }
    Vector::~Vector()
    {
    }
    void Vector::polar_mode()
    {
        mode = POL;
    }
    void Vector::rect_mode()
    {
        mode = RECT;
    }
    Vector Vector::operator+(const Vector& b) const
    {
        return Vector(x + b.x, y + b.y);
    }
    Vector Vector::operator-(const Vector& b) const
    {
        return Vector(x - b.x, y - b.y);
    }
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }
    Vector operator*(double n, const Vector& a)
    {
        return a * n;
    }
    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;
    }
}
main():
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Topic2.h"
using namespace std;
int main()
{
    using namespace VECTOR02;
    srand(time(0));
    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 << "Enetr 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";
        cout << result << endl;
        result.polar_mode();
        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";
    cin.clear();
    while (cin.get() != '\n')
        continue;
    return 0;
}
3.修改程序清单11.15,使之报告N次测试中的最高、最低和平均步数(其中N是用户输入的整数),而不是报告每次测试的结果。
.h:
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR03
{
    class Vector
    {
    public:
        enum Mode { RECT, POL };
    private:
        double x;
        double y;
        double mag;
        double ang;
        Mode mode;
        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; }
        double yval() const { return y; }
        double magval() const { return mag; }
        double angval() const { return ang; }
        void polar_mode();
        void rect_mode();
        Vector operator+(const Vector& b) const;
        Vector operator-(const Vector& b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
        friend Vector operator*(double n, const Vector& a);
        friend std::ostream& operator<<(std::ostream& os, const Vector& v);
    };
}
#endif
.cpp:
#include <cmath>
#include "Topic3.h"
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;
namespace VECTOR03
{
    const double Rad_to_deg = 45.0 / atan(1.0);
    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);
    }
    void Vector::set_x()
    {
        x = mag * cos(ang);
    }
    void Vector::set_y()
    {
        y = mag * sin(ang);
    }
    Vector::Vector()
    {
        x = y = mag = ang = 0.0;
        mode = RECT;
    }
    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;
        }
    }
    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()
    {
    }
    void Vector::polar_mode()
    {
        mode = POL;
    }
    void Vector::rect_mode()
    {
        mode = RECT;
    }
    Vector Vector::operator+(const Vector& b) const
    {
        return Vector(x + b.x, y + b.y);
    }
    Vector Vector::operator-(const Vector& b) const
    {
        return Vector(x - b.x, y - b.y);
    }
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }
    Vector operator*(double n, const Vector& a)
    {
        return a * n;
    }
    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;
    }
}
main():
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Topic3.h"
using namespace std;
const int number = 20;
int main()
{
    unsigned long a[number];
    using namespace VECTOR03;
    srand(time(0));
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;
    int ii = 0;
    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
        cout << "Enetr step length: ";
        if (!(cin >> dstep))
        {
            break;
        }
        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
        }
        a[ii] = steps;
        ii++;
        cout << "After " << steps << " steps, the subject has the following location:\n";
        cout << result << endl;
        result.polar_mode();
        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): ";
    }
    unsigned long max = a[0];
    unsigned long min = a[0];
    unsigned long sum = 0;
    for (int i = 0; i < ii; i++)
    {
        max >= a[i] ? max = max : max = a[i];
    }
    for (int i = 0; i < ii; i++)
    {
        min <= a[i] ? min = min : min = a[i];
    }
    for (int i = 0; i < ii; i++)
    {
        sum+=a[i];
    }
    cout << "最长步长:" << max << " 最短步长:" << min << " 平均步长:" << sum / ii<<endl;
    cout << "Bye!\n";
    cin.clear();
    while (cin.get() != '\n')
        continue;
    return 0;
}
4.重新编写最后的Time类示例(程序清单11.10、程序清单11.11和程序清单11.12),使用友元函数来实现所有的重载运算符。
.h:
#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& t1, const Time& t2);
    friend Time operator-(const Time& t1, const Time& t2);
    friend Time operator*(const Time& t, double n);
    friend Time operator*(double m, const Time& t);
    friend std::ostream& operator<<(std::ostream& os, const Time& t);
};
#endif
.cpp:
#include "Topic4.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& t1, const Time& t2)
{
    Time sum;
    sum.minutes = t1.minutes + t2.minutes;
    sum.hours = t1.hours + t2.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}
Time operator-(const Time& t1, const Time& t2)
{
    Time diff;
    int tot1, tot2;
    tot1 = t1.minutes + 60 * t1.hours;
    tot2 = t2.minutes + 60 * t2.hours;
    diff.minutes = (tot2 - tot1) % 60;
    diff.hours = (tot2 - tot1) / 60;
    return diff;
}
Time operator*(const Time& t, double mult)
{
    Time result;
    long totalminutes = t.hours * mult * 60 + t.minutes * mult;
    result.minutes = totalminutes % 60;
    result.hours = totalminutes / 60;
    return result;
}
Time operator*(double mult, const Time& t)
{
    Time result;
    long totalminutes = t.hours * mult * 60 + t.minutes * mult;
    result.minutes = totalminutes % 60;
    result.hours = totalminutes / 60;
    return result;
}
std::ostream& operator<<(std::ostream& os, const Time& t)
{
    os << t.hours << " hours, " << t.minutes << " minutes";
    return os;
}
.main():
#include <iostream>
#include "Topic4.h"
int main()
{
    using std::cout;
    using std::endl;
    Time aida(1, 55);
    Time tosca(3, 21);
    Time temp;
    cout << "Aida and Tosca:\n";
    cout << aida << "; " << tosca << endl;
    temp = aida + tosca;
    cout << "Aida + Tosca: " << temp << endl;
    temp = aida * 1.17;
    cout << "Aida * 1.17: " << temp << endl;
    cout << "10.0 * Tosca: " << 10.0 * tosca << endl;
    return 0;
}
5.重新编写Stonewt类(程序清单11.16和程序清单11.17),使它有一个状态成员,由该成员控制对象应转换为英石格式、整数磅格式还是浮点磅格式。重载 << 运算符,使用它来替换show_stn()和show_lbs()方法。重载加法、减法和乘法运算符,以便可以对Stonewt值进行加、减、乘运算。编写一个使用所有类方法和友元的小程序,来测试这个类。
.h:
#ifndef STONEWT_H_
#define STONEWT_H_
#include <iostream>
using namespace std;
class Stonewt
{
private:
    enum { Lbs_per_stn = 14 };
    int state;
    int stone;
    double pds_left;
    double pounds;
public:
    Stonewt(double lbs);
    Stonewt(int stn, double lbs);
    Stonewt();
    ~Stonewt();
    void setstate(int x);
    friend Stonewt operator+(const Stonewt& s1, const Stonewt& s2);
    friend Stonewt operator-(const Stonewt& s1, const Stonewt& s2);
    friend Stonewt operator*(const Stonewt& s, double n);
    friend Stonewt operator*(double m, const Stonewt& s);
    friend std::ostream& operator<<(std::ostream& os, const Stonewt& s);
};
#endif
.cpp:
#include <iostream>
#include "Topic5.h"
Stonewt::Stonewt(double lbs)
{
    stone = int(lbs) / Lbs_per_stn;
    pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
    pounds = lbs;
}
Stonewt::Stonewt(int stn, double lbs)
{
    stone = stn;
    pds_left = lbs;
    pounds = stn * Lbs_per_stn + lbs;
}
Stonewt::Stonewt()
{
    stone = pounds = pds_left = 0;
    state = 3;
}
Stonewt::~Stonewt()
{
}
void Stonewt::setstate(int x)
{
    state = x;
}
Stonewt operator+(const Stonewt& s1, const Stonewt& s2)
{
    Stonewt sum;
    sum.pounds = s1.pounds + s2.pounds;
    sum.stone = int(sum.pounds) / 14;
    sum.pds_left = int(sum.pounds) % 14 + sum.pounds - int(sum.pounds);
    return sum;
}
Stonewt operator-(const Stonewt& s1, const Stonewt& s2)
{
    double pounds;
    pounds = s1.pounds - s2.pounds;
    Stonewt diff(pounds);
    return diff;
}
Stonewt operator*(const Stonewt& s, double n)
{
    double pounds;
    pounds = s.pounds * n;
    Stonewt mult(pounds);
    return mult;
}
Stonewt operator*(double m, const Stonewt& s)
{
    return s * m;
}
std::ostream& operator<<(std::ostream& os, const Stonewt& s)
{
    if (s.state == 1)
    {
        os << s.stone << " stone, " << s.pds_left << " pounds\n";
    }
    if (s.state == 2)
    {
        os << int(s.pounds) << " pounds\n";
    }
    if (s.state == 3)
    {
        os << s.pounds << " pounds\n";
    }
    return os;
}
.main():
#include <iostream>
#include "Topic5.h"
using namespace std;
int main()
{
    Stonewt s[3];
    Stonewt s1(275);
    Stonewt s2(285.7);
    Stonewt s3(21, 8);
    s[0] = s1;
    s[1] = s2;
    s[2] = s3;
    int state;
    for (int i = 0; i < 3; i++)
    {
        cout << "#" << i + 1 << ": \n";
        cout << "Choose your style to display( '1' for stones, '2' for integer pounds, '3' for float pounds, others to quit): ";
        cin >> state;
        if (state != 1 && state != 2 && state != 3)
        {
            cout << "Warning: style can't satisfied!" << endl;
            cout << "Bye!\n";
            system("pause");
            return 0;
        }
        s[i].setstate(state);
        cout << "s" << i + 1 << ": " << s[i] << endl;
    }
    int st;
    cout << "Choose your style to display the result( '1' for stones, '2' for integer pounds, '3' for float pounds, others to quit): ";
    cin >> st;
    Stonewt sum;
    sum = s1 + s2;
    sum.setstate(st);
    cout << "s1 + s2 = " << sum << endl;
    Stonewt diff;
    diff = s3 - s2;
    diff.setstate(st);
    cout << "s3 - s2 = " << diff << endl;
    Stonewt mult1, mult2;
    mult1 = 10 * s1;
    mult2 = s3 * 1.5;
    mult1.setstate(st);
    mult2.setstate(st);
    cout << "10 * s1 = " << mult1 << endl;
    cout << "s3 * 1.5 = " << mult2 << endl;
    return 0;
}
6. 重新编写Stonewt类(程序清单11.16和程序清单11.17),重载全部6个关系运算符。运算符对pounds成员进行比较,并返回一个bool值。编写一个程序,它声明一个包含6个Stonewt对象的数组,并在数组声明初始化前3个对象。然后使用循环来读取用于设置剩余3个数组元素的值。接着报告最小的元素、最大的元素以及大于或等于11英石的元素的数量(最简单的方法是创建一个Stonewt对象,并将其初始化为11英石,然后将其同其他对象进行比较)。
.h:
#ifndef STONEWT_H_
#define STONEWT_H_
#include <iostream>
using namespace std;
class Stonewt02
{
private:
    enum { Lbs_per_stn = 14 };
    int state;
    int stone;
    double pds_left;
    double pounds;
public:
    Stonewt02(double lbs);
    Stonewt02(int stn, double lbs);
    Stonewt02();
    ~Stonewt02();
    void setstate(int x);
    friend bool operator<(const Stonewt02& s1, const Stonewt02& s2);
    friend bool operator>(const Stonewt02& s1, const Stonewt02& s2);
    friend bool operator==(const Stonewt02& s1, const Stonewt02& s2);
    friend bool operator<=(const Stonewt02& s1, const Stonewt02& s2);
    friend bool operator>=(const Stonewt02& s1, const Stonewt02& s2);
    friend bool operator!=(const Stonewt02& s1, const Stonewt02& s2);
    friend std::ostream& operator<<(std::ostream& os, const Stonewt02& s);
};
#endif
.cpp:
#include <iostream>
#include "Topic6.h"
using std::cout;
Stonewt02::Stonewt02(double lbs)
{
    stone = int(lbs) / Lbs_per_stn;
    pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
    pounds = lbs;
    state = 1;
}
Stonewt02::Stonewt02(int stn, double lbs)
{
    stone = stn;
    pds_left = lbs;
    pounds = stn * Lbs_per_stn + lbs;
    state = 1;
}
Stonewt02::Stonewt02()
{
    stone = pounds = pds_left = 0;
    state = 1;
}
Stonewt02::~Stonewt02()
{
}
void Stonewt02::setstate(int x)
{
    state = x;
}
bool operator<(const Stonewt02& s1, const Stonewt02& s2)
{
    if (s1.pounds < s2.pounds)
        return true;
    else
        return false;
}
bool operator>(const Stonewt02& s1, const Stonewt02& s2)
{
    if (s1.pounds > s2.pounds)
        return true;
    else
        return false;
}
bool operator==(const Stonewt02& s1, const Stonewt02& s2)
{
    if (s1.pounds == s2.pounds)
        return true;
    else
        return false;
}
bool operator<=(const Stonewt02& s1, const Stonewt02& s2)
{
    if (s1.pounds <= s2.pounds)
        return true;
    else
        return false;
}
bool operator>=(const Stonewt02& s1, const Stonewt02& s2)
{
    if (s1.pounds >= s2.pounds)
        return true;
    else
        return false;
}
bool operator!=(const Stonewt02& s1, const Stonewt02& s2)
{
    if (s1.pounds != s2.pounds)
        return true;
    else
        return false;
}
std::ostream& operator<<(std::ostream& os, const Stonewt02& s)
{
    if (s.state == 1)
    {
        os << s.stone << " stone, " << s.pds_left << " pounds";
    }
    if (s.state == 2)
    {
        os << int(s.pounds) << " pounds";
    }
    if (s.state == 3)
    {
        os << s.pounds << " pounds";
    }
    return os;
}
.main():
#include <iostream>
#include "Topic6.h"
int main()
{
    Stonewt02 s[6] = { {275}, {288.22}, {26, 7} };
    for (int i = 3; i < 6; i++)
    {
        double pounds;
        cout << "Please enter the last 3 Stonewt class members(enter the entire pounds): \n";
        cout << "#" << i + 1 << ": ";
        cin >> pounds;
        s[i] = pounds;
    }
    cout << "Enter finished!\n\n";
    cout << "So the whole 6 Stonewt class members are: \n";
    cout << "#1: " << s[0] << endl;
    cout << "#2: " << s[1] << endl;
    cout << "#3: " << s[2] << endl;
    cout << "#4: " << s[3] << endl;
    cout << "#5: " << s[4] << endl;
    cout << "#6: " << s[5] << endl;
    Stonewt02 mins = 65535;
    Stonewt02 maxs = 0;
    int num = 0;
    Stonewt02 flag(11, 0);
    for (int i = 0; i < 6; i++)
    {
        if (s[i] < mins)
            mins = s[i];
        if (s[i] > maxs)
            maxs = s[i];
        if (s[i] >= flag)
            num++;
    }
    cout << "After comparation:\n";
    cout << "The maximum Stonewt class member is " << maxs << endl;
    cout << "The minimum Stonewt class member is " << mins << endl;
    cout << "There are " << num << " Stonewt class members bigger than 11 stones" << endl;
    cout << endl;
    cout << "Comparation finished!\nBye!\n";
    return 0;
}
7.复数由两个部分组成:实数部分和虚数部分。复数的一种书写方式是:(3.0, 4.0),其中,3.0 是实数部分。4.0 是虚数部分。假设a = (A, Bi),c = (C, Di),则下面是一些复数运算:
加法: a + c = (A + C, (B + D)i)
减法: a - c = (A + C, (B + D)i)
乘法: a * c = (A * C - B * D, (A * D + B * C)i)
数乘: x * c = (x * C, x * Di)
共轭: ~a = (A, -Bi)
请定义一个复数类,以便下面的程序可以使用它来获得正确的结果。
#include
using namespace std;
#include “complex0.h” // to avoid confusion with complex.h
int main()
{
complex a(3.0, 4.0); // initialize to (3,4i)
complex 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”;
return 0;
}
注意,必须重载运算符 << 和 >> 。标准C++头文件complex提供了比这个示例更广泛的复数支持,因此应将自定义的头文件命名为complex0.h,以免发生冲突。应尽可能使用const。下面是该程序的运行情况。
Enter a complex number(q to quit) :
real: 10
imaginary : 12
c is(10, 12i)
complex conjugate is(10, -12i)
a is(3, 4i)
a + c is(13, 16i)
a - c is(-7, -8i)
a * c is(-18, 76i)
2 * c is(20, 24i)
Enter a complex number(q to quit) :
real: q
Done!
请注意,经过重载后,cin >> c将提示用户输入实数部分和虚数部分。
.h:
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include <iostream>
using namespace std;
class complex
{
private:
    double real;
    double ima;
public:
    complex();
    complex(double x, double y);
    ~complex();
    friend complex operator+(const complex& c1, const complex& c2);
    friend complex operator-(const complex& c1, const complex& c2);
    friend complex operator*(double n, const complex& c);
    friend complex operator*(const complex& c1, const complex& c2);
    friend complex operator~(const complex& c);
    friend std::ostream& operator<<(std::ostream& os, const complex& c);
    friend std::istream& operator>>(std::istream& is, complex& c);
};
#endif
.cpp:
#include <iostream>
#include "Topic7.h"
complex::complex()
{
    real = ima = 0.0;
}
complex::complex(double x, double y)
{
    real = x;
    ima = y;
}
complex::~complex()
{
}
complex operator+(const complex& c1, const complex& c2)
{
    complex sum;
    sum.real = c1.real + c2.real;
    sum.ima = c1.ima + c2.ima;
    return sum;
}
complex operator-(const complex& c1, const complex& c2)
{
    complex diff;
    diff.real = c1.real - c2.real;
    diff.ima = c1.ima - c2.ima;
    return diff;
}
complex operator*(const complex& c1, const complex& c2)
{
    complex mult;
    mult.real = c1.real * c2.real - c1.ima * c2.ima;
    mult.ima = c1.real * c2.ima + c1.ima * c2.real;
    return mult;
}
complex operator*(double n, const complex& c)
{
    complex mult;
    mult.real = n * c.real;
    mult.ima = n * c.ima;
    return mult;
}
complex operator~(const complex& c)
{
    complex conj;
    conj.real = c.real;
    conj.ima = -c.ima;
    return conj;
}
std::ostream& operator<<(std::ostream& os, const complex& c)
{
    os << "(" << c.real << "," << c.ima << "i)";
    return os;
}
std::istream& operator>>(std::istream& is, complex& c)
{
    cout << "real: ";
    is >> c.real;
    if (!is)
        return is;
    cout << "imaginary: ";
    is >> c.ima;
    return is;
}
.main():
#
#include <iostream>
#include "Topic7.h"
int main()
{
    complex a(3.0, 4.0);
    complex 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";
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值