C++ Primer Plus第六版编程题(第11章)

C++ Primer Plus第六版编程题(第11章)

    • 题目
    • 程序

题目

修改程序清单11.15,使之将一系列连续的随机漫步者位置写入到文件中。对于每个位置,用步号进行标示。另外,让该程序将初始条件(目标距离和步长)以及结果小结写入到该文件中。该文件的内容与下面类似:
(……内容省略……)

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

修改程序清单11.15,使之报告N次测试中的最高、最低和平均步数(其中N是用户输入的整数),而不是报告每次测试的结果。

重新编写最后的Time类示例(程序清单11.10、程序清单11.11和程序清单11.12),使用友元函数来实现所有的重载运算符。

重新编写Stonewt类(程序清单11.16和程序清单11.17),使它有一个状态成员,由该成员控制对象应转换为英石格式、整数磅格式还是浮点磅格式。重载<<运算符,使用它来替换show_stn()和show_lbs()方法。重载加法、减法和乘法运算符,以便可以对Stonewt值进行加、减、乘运算。编写一个使用所有类方法和友元的小程序,来测试这个类。

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

复数有两个部分组成:实数部分和虚数部分。复数的一种书写方式是:(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),其中x为实数。
共轭:~a=(A,-Bi)。
请定义一个复数类,以便下面的程序可以使用它来获得正确的结果。
(……代码省略……)
注意。必须重载运算符<<和>>。标准C++使用头文件complex提供了比这个示例更广泛的复数支持,因此应将自定义的头文件命名为complex0.h,以免发生冲突。应尽可能使用const。
下面是该程序的运行情况。
(……代码省略……)
请注意,经过重载后,cin>>c将提示用户输入实数和虚数部分。

程序

1.vector.h与vector.cpp无需修改

// vector.h -- 不用修改 
#ifndef VECTOR_H_
#define VECTOR_H_
#include 
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
// vector.cpp -- 不用修改 
#include 
#include "vector.h"   // includes 
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
//main.cpp
#include 
#include  
#include       // rand(), srand() prototypes
#include         // time() prototype
#include "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;
    ofstream fout;
    fout.open("RandWalk.txt");
    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
        cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
        else
        {
        	fout<<"Target Distance: "<<target<<", Step Size: "<<dstep<<endl;
         	fout<<steps<<": "<<result<<endl;
		}

        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
        	fout<<steps<<": "<<result<<endl;
        }
        cout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        cout << result << endl;
        fout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        fout << result << endl;
        result.polar_mode();
        cout << " or\n" << result << endl;
        cout << "Average outward distance per step = "
            << result.magval()/steps << endl;
        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";
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}
// vect.h
#ifndef VECTOR_H_
#define VECTOR_H_
#include 
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
        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;}       // 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 
#include 
#include "vect.h"   // includes 
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
    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;
    }

    // set x from polar coordinate
    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;
             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;
        }
    }

    // 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)
        {
        	 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()    // destructor
    {
    }
    
    double Vector::magval() const 
	{
		double mag;
		mag = sqrt(x * x + y * y);
		return mag; 
	} 
	  			  
    double Vector::angval() const 
    {
    	double ang;
    	if (x == 0.0 && y == 0.0)
            ang = 0.0;
        else
            ang = atan2(y, x);
        return ang;
	}

    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
//main.cpp -- using the Vector class
// compile with the vect.cpp file
#include 
#include       // rand(), srand() prototypes
#include         // time() prototype
#include "vect.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)
    {
        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";
        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";
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}

3.vector.h与vector.cpp无需修改

// vector.h -- 不用修改 
#ifndef VECTOR_H_
#define VECTOR_H_
#include 
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
// vector.cpp -- 不用修改 
#include 
#include "vector.h"   // includes 
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
//main.cpp
// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include 
#include       // rand(), srand() prototypes
#include         // time() prototype
#include "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<<"How many times: ";
    int N;
    cin>>N;
    int max=0;
    int min=9999;
    int sum=0;
    double average;
    cout << "Enter target distance (q to quit): ";
    cin>>target;
    cout << "Enter step length: ";
    cin>>dstep;
    
    for(int i=0;i<N;i++)
    {
    	while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
        }
        max=max>steps?max:steps;
        min=min<steps?min:steps;
        sum+=steps;
        steps = 0;
        result.reset(0.0, 0.0);
	}
	average=double(sum)/N;
	cout<<"The max steps is: "<<max<<endl;
	cout<<"The min steps is: "<<min<<endl;
	cout<<"The average steps is: "<<average<<endl;
    cout << "Bye!\n";
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}
// mytime.h -- Time class with friends
#ifndef MYTIME3_H_
#define MYTIME3_H_
#include 

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)
        { return t * m; }   // inline definition
    friend std::ostream & operator<<(std::ostream & os, const Time & t);

};
#endif
// 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 & 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.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; 
}
//main.cpp
//usetime3.cpp -- using the fourth draft of the Time class
// compile usetime3.cpp and mytime3.cpp together
#include 
#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; 
}
// 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 state;
    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();
    void Setstate(int x);
    Stonewt operator+(const Stonewt & s)const;
    Stonewt operator-(const Stonewt & s)const;
    Stonewt operator*(double n)const;
    friend Stonewt operator*(double m, const Stonewt & s)
        { return s * m; }   // inline definition
    friend std::ostream & operator<<(std::ostream & os, const Stonewt & s);
};
#endif
// stonewt.cpp -- Stonewt methods
#include 
using std::cout;
#include "stonewt.h"

// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
	state=1; 
    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)
{
	state=-1;
    stone = stn;
    pds_left = lbs;
    pounds =  stn * Lbs_per_stn +lbs;
}

Stonewt::Stonewt()          // default constructor, wt = 0
{
	state=0;
    stone = pounds = pds_left = 0;
}

Stonewt::~Stonewt()         // destructor
{
}

void Stonewt::Setstate(int x)
{
	state=x;
}

Stonewt Stonewt::operator+(const Stonewt & s) const
{
	Stonewt sum;
    sum.pounds = pounds + s.pounds;
    sum.stone = int(sum.pounds) / Lbs_per_stn;
    sum.pds_left = int(sum.pounds) % Lbs_per_stn + sum.pounds - int(sum.pounds);
    return sum;
    
    //The other method
//    double tot;
//    tot=pounds + s.pounds;
//    Stonewt sum(tot);
//    return sum;
}

Stonewt Stonewt::operator-(const Stonewt & s) const
{
	Stonewt diff;
	diff.pounds=pounds-s.pounds;
	diff.stone = int(diff.pounds) / Lbs_per_stn;
    diff.pds_left = int(diff.pounds) % Lbs_per_stn + diff.pounds - int(diff.pounds);
    return diff;
}

Stonewt Stonewt::operator*(double n) const
{
    double mult;
    mult=pounds*n;
    return Stonewt(mult);
}

std::ostream & operator<<(std::ostream & os, const Stonewt & s)
{
    if (s.state == -1)
    {
        os << s.stone << " stone, " << s.pds_left << " pounds\n";
    }
    else if (s.state == 0)
    {
        os << int(s.pounds) << " pounds\n";
    }
    else if (s.state == 1)
    {
        os << s.pounds << " pounds\n";
    }
    else
        os << "Stonewt state is invalid";
    return os; 
}
//main.cpp
// stone.cpp -- user-defined conversions
// compile with stonewt.cpp
#include 
using std::cout;
using std::cin;
#include "stonewt.h"
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 celebrity weighed: "<<incognito;
    cout << "The detective weighed: "<<wolfe;
    cout << "The President weighed: "<<taft;
    
    Stonewt tf(1.6);
    Stonewt sum,diff,mult;
    sum=incognito+tf;
    diff=wolfe-tf;
    mult=taft*1.6;
   
    cout<<"Choose your style to display the result( '-1' for stones, '0' for integer pounds, '1' for float pounds): ";
    int st;
    cin>>st;
    cout << "After dinner, the celebrity weighed: ";
    sum.Setstate(st);
    cout<<sum;
    cout << "After sport, the detective weighed: ";
    diff.Setstate(st);
    cout<<diff;
    cout << "Now,the detective weighed: ";
    mult.Setstate(st);
    cout<<mult;
    // std::cin.get();
    return 0;
}
// stonewt6.h -- definition for the Stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
    enum {Lbs_per_stn = 14};      // pounds per stone
    int state;
    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();
    void Setstate(int x);
    friend bool operator>(const Stonewt & s1,const Stonewt & s2);
    friend bool operator<(const Stonewt & s1,const Stonewt & s2);
    friend bool operator>=(const Stonewt & s1,const Stonewt & s2);
    friend bool operator<=(const Stonewt & s1,const Stonewt & s2);
    friend bool operator==(const Stonewt & s1,const Stonewt & s2);
    friend bool operator!=(const Stonewt & s1,const Stonewt & s2);
    friend std::ostream & operator<<(std::ostream & os, const Stonewt & s);
};
#endif
// stonewt.cpp -- Stonewt methods
#include 
using std::cout;
#include "stonewt6.h"

// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
	state=-1; 
    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)
{
	state=-1;
    stone = stn;
    pds_left = lbs;
    pounds =  stn * Lbs_per_stn +lbs;
}

Stonewt::Stonewt()          // default constructor, wt = 0
{
	state=-1;
    stone = pounds = pds_left = 0;
}

Stonewt::~Stonewt()         // destructor
{
}

void Stonewt::Setstate(int x)
{
	state=x;
}

bool operator>(const Stonewt & s1,const Stonewt & s2)
{
	if(s1.pounds>s2.pounds)
		return true;
	else
		return false;
} 

bool operator<(const Stonewt & s1,const Stonewt & s2)
{
	if(s1.pounds<s2.pounds)
		return true;
	else
		return false;
}

bool operator>=(const Stonewt & s1,const Stonewt & s2)
{
	if(s1.pounds>=s2.pounds)
		return true;
	else
		return false;
}

bool operator<=(const Stonewt & s1,const Stonewt & s2)
{
	if(s1.pounds<=s2.pounds)
		return true;
	else
		return false;
}

bool operator==(const Stonewt & s1,const Stonewt & s2)
{
	if(s1.pounds==s2.pounds)
		return true;
	else
		return false;
}

bool operator!=(const Stonewt & s1,const Stonewt & s2)
{
	if(s1.pounds!=s2.pounds)
		return true;
	else
		return false;
}

std::ostream & operator<<(std::ostream & os, const Stonewt & s)
{
    if (s.state == -1)
    {
        os << s.stone << " stone, " << s.pds_left << " pounds\n";
    }
    else if (s.state == 0)
    {
        os << int(s.pounds) << " pounds\n";
    }
    else if (s.state == 1)
    {
        os << s.pounds << " pounds\n";
    }
    else
        os << "Stonewt state is invalid";
    return os; 
}
//main.cpp
// stone.cpp -- user-defined conversions
// compile with stonewt.cpp
#include 
using std::cout;
using std::cin;
#include "stonewt6.h"
int main()
{
	Stonewt s[6]={{275},{285.7},{21,8}};
	cout<<"Enter the last three Stonewt:\n";
	for(int i=3;i<6;i++)
	{
		double pounds;
		cout<<"#"<<i+1<<": ";
		cin>>pounds;
		s[i]=pounds;
	}
	
	Stonewt max=s[0];
	Stonewt min=s[0];
	const Stonewt flag(11,0);
	int count=0;
	for(int i=0;i<6;i++)
	{
		max=max>s[i]?max:s[i];
		min=min<s[i]?min:s[i];
//		if (s[i] < min)
//            min = s[i];
//        if (s[i] > max)
//            max = s[i];
		if(s[i]>=flag)
			count++;
	}
	
    cout<<"The max is: "<<max;
	cout<<"The min is: "<<min;
	cout<<"There are "<<count<<" memeber bigger than 11 stone.\n"; 
    // std::cin.get();
    return 0;
}
//complex0.h
#ifndef COMPLEX0_H_
#define COMPLEX0_H_

class Complex
{
	private:
		double real;
		double imag;
	public:
		Complex();
		Complex(double m,double n);
		~Complex();
		Complex operator+(const Complex & n)const;
		Complex operator-(const Complex & n)const;
		Complex operator*(const Complex & n)const;
		Complex operator*(double n)const;
		friend Complex operator*(double n,const Complex &m)
		{return m*n;}
		Complex operator~()const;
		friend std::ostream & operator<<(std::ostream & os, const Complex & n);
		friend std::istream & operator>>(std::istream & is, Complex & n);
};
#endif
//complex0.cpp
#include 
#include "complex0.h"
using std::cout;
using std::cin;

Complex::Complex()
{
	real=imag=0.0;
}
Complex::Complex(double m,double n)
{
	real=m;
	imag=n;
}
Complex::~Complex()
{
}
Complex Complex::operator+(const Complex & n)const
{
	Complex sum;
	sum.real=real+n.real;
	sum.imag=imag+n.imag;
	return sum;
}
Complex Complex::operator-(const Complex & n)const
{
	Complex diff;
	diff.real=real-n.real;
	diff.imag=imag-n.imag;
	return diff;
 } 
Complex Complex::operator*(const Complex & n)const
{
	Complex mult1;
	mult1.real=real*n.real-imag*n.imag;
	mult1.imag=real*n.imag+imag*n.real;
	return mult1;
}
Complex Complex::operator*(double n)const
{
	Complex mult;
	mult.real=real*n;
	mult.imag=imag*n;
	return mult;
}
Complex Complex::operator~()const
{
	Complex conj;
	conj.real=real;
	conj.imag=-imag;
	return conj;
}
std::ostream & operator<<(std::ostream & os, const Complex & n)
{
	os<<"("<<n.real<<", "<<n.imag<<"i)";
	return os;
}
std::istream & operator>>(std::istream & is, Complex & n)
{
	cout<<"real: ";
	is>>n.real;
	cout<<"imaginary: ";
	is>>n.imag;
	return is;
}
//main.cpp
#include 
using namespace std;
#include "complex0.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;
}

你可能感兴趣的:(c++)