1. 程式人生 > >c++ primer plus第十一章習題答案

c++ primer plus第十一章習題答案

第一題

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_

#include <iostream>
#include <cmath>

using std::sqrt;
using std::atan2;
using std::cos;
using std::sin;

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() {mag = sqrt(x*x + y*y);}
		void set_ang() {if(x==0.0&&y==0.0) ang = 0.0; else ang = atan2(y,x);}
		void set_x() {x = mag*cos(ang);}
		void set_y() {y = mag*sin(ang);}
	public:
		Vector();
		Vector(double n1, double n2, Mode form = RECT);
		~Vector();
		void reset(double n1, double n2, Mode form = RECT);
		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"

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

	// 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;
		}
	}

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

	// reset vector from rectangular coordinates if frm 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;
		}
	}

	void Vector::polar_mode()		// set to polar mode
	{
		mode = POL;
	}

	void Vector::rect_mode()		// set to rectangular mode
	{
		mode = RECT;
	}

	// operator overlaoading
	// 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;
	}
}

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include "vector.h"

int main()
{
	using namespace std;
	using VECTOR::Vector;
	srand(time(NULL));
	double direction;
	Vector step;
	Vector result(0.0, 0.0);
	unsigned long steps = 0;
	double target;
	double dstep;

	ofstream fout("vector.txt", ios::out | ios::app);// create object for output
													// associate with a file
	if(!fout.is_open())				// check if the file can be writen
	{
		cerr << "Open file fail!\n";
		exit(EXIT_FAILURE);
	}
	else
	{
		cout << "Open file successfully!\n";
	}

	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.rect_mode();
			fout << steps << ": " << result << "\n";
			result = result + step;
			steps++;
		}

		// display in screen
		result.rect_mode();
		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;

		// write into txt file
		fout << steps << ": (x, y) = (" << result.xval() << ", " << result.yval() << ")\n";
		fout << "After " << steps << " steps, the subject "
			"has the following location:\n";
		result.rect_mode();
		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();
	fout.close();				// done with file
	while(cin.get() != '\n')
		continue;
	return 0;
}


第二題

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_

#include <iostream>
#include <cmath>

using std::sqrt;
using std::atan2;
using std::cos;
using std::sin;

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() {mag = sqrt(x*x + y*y);}
		//void set_ang() {if(x==0.0&&y==0.0) ang = 0.0; else ang = atan2(y,x);}
		double set_x(double mag, double ang) {return mag*cos(ang);}// give mag and ang, calculate x, y
		double set_y(double mag, double ang) {return mag*sin(ang);}
	public:
		Vector();
		Vector(double n1, double n2, Mode form = RECT);
		~Vector();
		void reset(double n1, double n2, Mode form = RECT);
		double xval() const {return x;}		// report x value
		double yval() const {return y;}		// report y value
		double magval() const {return sqrt(x*x + y*y);}	// report magnitude
		double angval() const {if(x==0.0&&y==0.0) return 0.0;else return atan2(y,x);}	// 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"

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

	// 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)
		{
			double mag = n1;// temporary variable
			double ang = n2 / Rad_to_deg;
			x = set_x(mag, ang);// calculate and save x and y
			y = 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
	{
		//
	}

	// reset vector from rectangular coordinates if frm 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)
		{
			double mag = n1;
			double ang = n2 / Rad_to_deg;
			x = set_x(mag, ang);
			y = 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::polar_mode()		// set to polar mode
	{
		mode = POL;
	}

	void Vector::rect_mode()		// set to rectangular mode
	{
		mode = RECT;
	}

	// operator overlaoading
	// 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() << ", "// use public interface to get mag and ang
				<< v.angval() * Rad_to_deg << ")";
		}
		else
			os << "Vector object mode is invalid";
		return os;
	}
}

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "vector.h"

int main()
{
	using namespace std;
	using VECTOR::Vector;
	srand(time(NULL));
	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";
	cin.clear();
	while(cin.get() != '\n')
		continue;
	return 0;
}


第三題

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_

#include <iostream>
#include <cmath>

using std::sqrt;
using std::atan2;
using std::cos;
using std::sin;

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() {mag = sqrt(x*x + y*y);}
		void set_ang() {if(x==0.0&&y==0.0) ang = 0.0; else ang = atan2(y,x);}
		void set_x() {x = mag*cos(ang);}
		void set_y() {y = mag*sin(ang);}
	public:
		Vector();
		Vector(double n1, double n2, Mode form = RECT);
		~Vector();
		void reset(double n1, double n2, Mode form = RECT);
		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"

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

	// 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;
		}
	}

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

	// reset vector from rectangular coordinates if frm 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;
		}
	}

	void Vector::polar_mode()		// set to polar mode
	{
		mode = POL;
	}

	void Vector::rect_mode()		// set to rectangular mode
	{
		mode = RECT;
	}

	// operator overlaoading
	// 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;
	}
}

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "vector.h"

int main()
{
	using namespace std;
	using VECTOR::Vector;
	srand(time(NULL));
	double direction;
	Vector step;
	Vector result(0.0, 0.0);
	unsigned long steps = 0;
	double target;
	double dstep;

	int N;
	int* pt;
	int min, max, avr=0;

	cout << "Enter target distance (q to quit): ";
	while(cin >> target)
	{
		cout << "Enter step length: ";
		if(!(cin >> dstep))
			break;
		cout << "Enter the number of cycle index: ";
		if(!(cin >> N))
			break;
		else
			if(N <= 0)	// check if N is positive
			{
				cout << "You should enter a positive number!\n";
				cout << "Enter target distance (q to quit): ";
				continue;
			}
		pt = new int [N];	// dynamic memory assignment
		for(int i = 0; i < N; i++)
		{
			while(result.magval() < target)
			{
				direction = rand() % 360;
				step.reset(dstep, direction, Vector::POL);
				result = result + step;
				steps++;
			}
			pt[i] = steps;
			steps = 0;				// in the next cycle the value of steps is 0
			result.reset(0.0, 0.0);	// in the next cycle result should be cleared
		}
		min = max = pt[0];
		for(int i = 1; i < N; i++)	// calculate and save the max, min and average
		{
			if(pt[i] < min)
				min = pt[i];
			if(pt[i] > max)
				max = pt[i];
			avr = pt[i] +avr;
		}
		avr = avr/N;
		cout << "Max steps is " << max << " while Min steps is " << min << endl;
		cout << "Average steps is " << avr << endl;
		delete [] pt;			// pointer pt should be deleted here
		cout << "Enter target distance (q to quit): ";
	}
	cout << "Bye!\n";
	cin.clear();
	while(cin.get() != '\n')
		continue;
	return 0;
}


第四題

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

#endif

// mytime3.cpp -- implementing Time methods
#include "mytime3.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& s, const Time& t)
{
	int minutes = s.minutes + t.minutes;
	int hours = s.hours + t.hours + minutes / 60;
	minutes %= 60;
	return Time(hours, minutes);
}

Time operator-(const Time& s, const Time& t)
{
	Time diff;
	int tot1, tot2;
	tot1 = t.minutes + 60 * t.hours;
	tot2 = s.minutes + 60 - s.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;
}

// usetime3.cpp -- using the fourth draft of the Time class
// compile usetime3.cpp and  mytime3.cpp together
#include <iostream>
#include "mytime3.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;

	return 0;
}


第五題

// stonewt.h -- definition for the Stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_

class Stonewt
{
public:
	enum Mode {STONE, PDS, POUND};	// status signal
private:
	enum {Lbs_per_stn = 14};	// pounds per stone
	Mode mode;
	int stone;					// whole stones
	double pds_left;			// fractional pounds
	double pounds;				// entire weight in pounds
public:
	explicit Stonewt(double lbs);	// constructor for double pounds
	Stonewt(int stn, double lbs);	// constructor for stone, lbs
	Stonewt();					// default constructor
	~Stonewt();
	//void show_lbs() const;			// show weight in pounds format
	//void show_stn() const;			// show weight in stone format

	void Status(const Mode & par = STONE) 
		{mode = par;}
	Stonewt operator+(const Stonewt& obj) const;
	Stonewt operator-(const Stonewt& obj) const;
	Stonewt operator*(const double& n) const;
	// friend
	friend Stonewt operator*(const double& n, const Stonewt& obj) 
		{return obj*n;}
	friend std::ostream& operator<<(std::ostream& os, const Stonewt& obj);
};

#endif

// stonewt.cpp -- Stonewt methods
#include <iostream>
#include "stonewt.h"

using std::cout;

// 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;
	mode = STONE;
}

// construct Stonewt object from stone, double values
Stonewt::Stonewt(int stn, double lbs)
{
	stone = stn;
	pds_left = lbs;
	pounds = stn * Lbs_per_stn + lbs;
	mode = STONE;
}

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

Stonewt::~Stonewt()		// destructor
{

}

Stonewt Stonewt::operator+(const Stonewt& obj) const
{
	return Stonewt(pounds + obj.pounds);
}

Stonewt Stonewt::operator-(const Stonewt& obj) const
{
	return Stonewt(pounds - obj.pounds);
}

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

std::ostream& operator<<(std::ostream& os, const Stonewt& obj)
{
	if(obj.mode == Stonewt::STONE)
		cout << "Stone of the object is " << obj.stone << std::endl;
	else if(obj.mode == Stonewt::PDS)
		cout << "Pds_left of the object is " << obj.pds_left << std::endl;
	else if(obj.mode == Stonewt::POUND)
		cout << "Pound of the object is " << obj.pounds << std::endl;
	else
	{
		cout << "Mode format is invalid!\n" << std::endl;
	}
	return os;
}


/*
// 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";
}
*/

#include <iostream>
#include "stonewt.h"

using namespace std;

int main()
{
	Stonewt member1(30.5);
	Stonewt member2(10, 13.4);
	Stonewt member3;
	Stonewt member4;

	member3 = Stonewt(35.51);
	cout << "member3, stone format: " << member3;
	member3.Status(Stonewt::PDS);
	cout << "member3, pds format: " << member3;
	member3.Status(Stonewt::POUND);
	cout << "member3, pound format: " << member3;

	member3 = 2*member3;
	member3.Status(Stonewt::STONE);
	cout << "member3 multiply 2, stone format: " << member3;
	
	cout << endl;
	cout << "member1: " << member1 
		<< "member2: " << member2;
	member4 = member1 + member2;
	cout << "member4 = member1 + member2: " << member4;

	member2 = member4 - member3;
	cout << "member2 = member4 - member3: " << member2;

	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 stone;					// whole stones
	double pds_left;			// fractional pounds
	double pounds;				// entire weight in pounds
public:
	explicit Stonewt(double lbs);	// constructor for double pounds
	Stonewt(int stn, double lbs);	// constructor for stone, lbs
	Stonewt();					// default constructor
	~Stonewt();
	//void show_lbs() const;			// show weight in pounds format
	//void show_stn() const;			// show weight in stone format

	bool operator>(const Stonewt& obj) const;
	bool operator>=(const Stonewt& obj) const;
	bool operator<(const Stonewt& obj) const;
	bool operator<=(const Stonewt& obj) const;
	bool operator==(const Stonewt& obj) const;
	bool operator!=(const Stonewt& obj) const;
	// friend
	friend std::ostream& operator<<(std::ostream& os, const Stonewt& obj);
};

#endif
// stonewt.cpp -- Stonewt methods
#include <iostream>
#include "stonewt.h"

using std::cout;

// 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& obj) const
{
	if(pounds > obj.pounds)
		return true;
	else
		return false;
}

bool Stonewt::operator>=(const Stonewt& obj) const
{
	if(pounds >= obj.pounds)
		return true;
	else
		return false;
}

bool Stonewt::operator<(const Stonewt& obj) const
{
	if(pounds < obj.pounds)
		return true;
	else
		return false;
}

bool Stonewt::operator<=(const Stonewt& obj) const
{
	if(pounds <= obj.pounds)
		return true;
	else
		return false;
}

bool Stonewt::operator==(const Stonewt& obj) const
{
	if(pounds == obj.pounds)
		return true;
	else
		return false;
}

bool Stonewt::operator!=(const Stonewt& obj) const
{
	if(pounds != obj.pounds)
		return true;
	else
		return false;
}

std::ostream& operator<<(std::ostream& os, const Stonewt& obj)
{
	cout << "Pound is " << obj.pounds << std::endl;
	return os;
}
/*
// 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";
}
*/

#include <iostream>
#include "stonewt.h"

using namespace std;

int main()
{
	Stonewt taft[6] = {
		Stonewt(55.5),
		Stonewt(100.1),
		Stonewt(200.2)
	};
	Stonewt ori = Stonewt(11, 0);
	Stonewt max, min;
	int count = 0;

	for(int i = 3; i < 6; i++)
	{
		taft[i] = Stonewt(i*3, i);
	}
	max = min = taft[0];
	for(int i = 0; i < 6; i++)
	{
		if(taft[i]>max)
			max = taft[i];
		if(taft[i]<min)
			min = taft[i];
		if(taft[i]>=ori)
			count++;
	}
	cout << "The Min element " << min;
	cout << "The Max element " << max;
	cout << count << " elements >= 11 Stone" << std::endl;
	return 0;
}



第七題

complex0.h
#ifndef COMPLEX0_H_
#define COMPLEX0_H_

class complex
{
private:
	double A;
	double B;
public:
	// constructor and destructor
	complex();
	complex(double i, double j);
	~complex();
	// overloading
	complex operator+(const complex& obj) const;
	complex operator-(const complex& obj) const;
	complex operator*(const complex& obj) const;
	complex operator*(const double& n) const;
	complex operator~() const;
	// friend
	friend complex operator*(const double& n, const complex& obj);
	friend std::ostream& operator<<(std::ostream& os, const complex& obj);
	friend std::istream& operator>>(std::istream& os, complex& obj);
};

complex0.cpp
<pre name="code" class="cpp">#include <iostream>
#include "complex0.h"

complex::complex()
{
	A = B = 0;
}

complex::complex(double i, double j)
{
	A = i;
	B = j;
}

complex::~complex()
{
	//
}

complex complex::operator+(const complex& obj) const
{
	return complex(A+obj.A, B+obj.B);
}

complex complex::operator-(const complex& obj) const
{
	return complex(A-obj.A, B-obj.B);
}

complex complex::operator*(const complex& obj) const
{
	return complex(A*obj.A-B*obj.B, A*obj.B+B*obj.A);
}

complex complex::operator*(const double& n) const
{
	return complex(A*n, B*n);
}

complex complex::operator~() const
{
	return complex(A, -B);
}

complex operator*(const double& n, const complex& obj)
{
	return obj*n;
}

std::ostream& operator<<(std::ostream& os, const complex& obj)
{
	std::cout << "(" << obj.A << ", " << obj.B << "i)";
	return os;
}

std::istream& operator>>(std::istream& os, complex& obj)
{
	std::cout << "real: ";
	if(std::cin >> obj.A)
	{
		std::cout << "imaginary: ";
		std::cin >> obj.B;
	}
	return os;
}
<span style="font-family: Arial, Helvetica, sans-serif;">main.cpp</span>
<pre name="code" class="cpp">#include <iostream>
#include "complex0.h"
using namespace std;

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;
}

#endif

相關推薦

c++ primer plus習題答案

第一題 // vect.h -- Vector class with <<, mode state #ifndef VECTOR_H_ #define VECTOR_H_ #include <iostream> #include <cmath

C Primer Plus 習題總結……2015.5.10

1、沒有加上字串結尾標誌 空字元'\0'; 2、#include<stdio.h> int main(void) {char note[]="See you at snack bar: ";char *ptr;ptr=note;puts(ptr);puts(++ptr);note[7]='\0'

C primer Plus---自學ing

在第十一章,學了許多輸入輸出的函式,這些函式各有自己的優點和缺點。 fgets()和fputs()函式 fgets()可以有三個引數,第一個是讀入的字串;第二個是指明讀入的字串的最大字元數;第三個指明要讀入的檔案。如果是以鍵盤讀入,則稱為標準輸入,用stdin

C Primer Plus 課後答案

目錄 複習題 程式設計練習 I doing this 複習題 1.哪些類別的變數可以成為它所在函式的區域性變數?

習題答案

linux第十一章練習題答案?1. 如何把 /etc/passwd 中用戶uid 大於500 的行給打印出來?awk -f ‘:‘ ‘$3 > 500‘ /etc/passwd?2. awk中 nr,nf兩個變量表示什麽含義awk -f ‘:‘ ‘{print $nr}‘ /etc/passwd 會打印

C++ PRimer PLUS六版)中文版 chapter11答案 參考

bject get quit primer rime 答案 std cat tar #include <iostream>#include <cstdlib>#include <ctime>#include "vector.h" int

C Primer Plus(6版)複習題答案

11.12複習題 下面字串的宣告有什麼問題? int main(void) { char name[] = {'F', 'e', 's', 's'}; //少了‘\0‘ char name[] = {'F', 'e', 's', 's', '\0'};

C++ primer plus 課後習題,原創答案

//第十章第一題 #ifndef GOLF_H_ #define GOLF_H_ #include<string> #include<iostream> using std::string; class BankCount { pri

c++ primer 習題

練習11.1 map下標是關鍵字,可以設定型別。vector下標是整數。 map的元素是pair, vector是一個單型別。 練習11.3 11.4 #include <iostream> #include <map> #include <

C Primer Plus 課後答案

目錄 複習題 a. b. a. b. 8.

C++ primer plus 物件和類

重要的面向物件程式設計特性:抽象、封裝和資料隱藏、多型、繼承和程式碼的可重用性。為了實現這些特性並將它們組合在一起,C++所做的最重要的改進是提供了類。 類是一種將抽象轉換為使用者定義型別的C++工具,它將資料表示和操縱資料的方法組合成一個整潔的包。 類宣告:以資料成員的方式描述資料部分,以

C++Primer五版 習題答案(1~10)

1:知識點1:物件生命週期:全域性物件在程式啟動時分配,在程式結束時銷燬。區域性自動物件,當我們進入其定義所在程式塊時被建立,在離開塊時被銷燬。區域性static物件在第一次使用前分配,在程式結束時銷

C Primer Plus ——陣列和指標

 與普通變數相似,在初始化之前陣列元素的數值是不定的。編譯器使用的數值是儲存單元中已有的數值。初始化陣列元素時(int),當數值數目少於陣列元素數目時(部分初始化),多餘的陣列元素被初始化為0。如果初始化列表中專案的個數大於陣列大小,編譯器則會認為這是一個錯誤。可以在初始化

c++ primer 筆記動態記憶體

第十二章:動態記憶體 梗概:本章主要講解使用C++智慧指標動態管理記憶體以及直接管理動態記憶體的方法以及他們的結合。 靜態記憶體儲存static變數以及定義在所有函式之外的變數。棧記憶體儲存函式之內的非static變數,堆記憶體用來分配給程式動態產生的物件。靜態記憶體和棧記憶體中的變數由編譯

c++ primer plus 六版程式設計練習答案

該章節第二題程式沒問題,但不懂為什麼 5.1 #include<stdafx.h> #include <iostream> using namespace std; int main() { int max, min; long long sum=0; co

c++ primer plus 六版程式設計練習答案

4.1 #include<stdafx.h> #include <iostream> #include<string> using namespace std; int main() { char f_name[10], l_name[10]; int

c++ Primer Plus 六版 程式設計練習答案

3.1 #include<stdafx.h> #include <iostream> using namespace std; const int inch_per_feet = 12;//一英尺(inch)等於12英寸(feet) int main() { int

c++ primer plus 六版程式設計練習答案第二

2.1 #include "stdafx.h" #include <iostream> using namespace std; int main() { char name[5],address[15]; cout << "enter your name\n"

C#圖解教程 列舉

列舉 列舉 列舉是由程式設計師定義的型別與類或結構一樣。 與結構一樣,列舉是值型別,因此直接儲存它們的資料,而不是分開儲存成引用和資料 列舉只有一種型別的成員:命名的整數值常量 例:列舉示例 關鍵字 列舉名稱 ↓ ↓ enum TrafficLight {

C++Primer5版課後習題答案

開發環境及工具:win7 + vs2010 如果有錯誤或者更好的寫法,互相學習交流,微訊號:WangXinBoy09 日常更新,慢慢來,別急 聯絡1.1 和 1.2 不會弄,1.2 寫了一個看不到效果 //練習1.3 1.4 1.5 #include <iost