小言_互联网的博客

第十章 编程练习 (C++ Primer Plus)

444人阅读  评论(0)

1.为复习题5描述的类提供方法定义,并编写一个小程序来演示所有的特性。

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

class Account{
	static const int ArrSize = 11;
	private:
		std::string name;
		std::string account;
		double withdraw;
	public:
		Account(std::string _name = "0000", std::string _account = "0000",
		double _withdraw = 0000);
		void ShowAccount() const;
		void SetWithdraw(double wd);
		void Withdraw(double wd);
};

Account::Account(std::string _name , std::string _account , 
				double _withdraw )
{
	name = _name;
	account = _account;
	withdraw = _withdraw;
}
void Account::ShowAccount() const
{
	cout << "name: " << name << endl;
	cout << "account number: " << account << endl;
	cout << "withdraw: " << withdraw << endl; 
}
void Account::SetWithdraw(double wd)
{
	withdraw = wd;		
}
void Account::Withdraw(double wd)
{
	if(withdraw < wd)
		cout << "you don't have enough money!"<<endl;
	else
		withdraw -= wd;
}

int main()
{
	Account account;
	account.ShowAccount();
	account.SetWithdraw(5668.9);
	account.ShowAccount();
	account.Withdraw(520);
	account.ShowAccount();
	return 0;
}

2.下面是一个非常简单的类定义:

class Person{
	private:
		static const LIMIT = 25;
		string lname;			//Person's last name
		char fname[LIMIT];		//Person's first name
	public:
		Person() {
			lname = " ";
			fname[0] = '\0'
		}//#1
		Person(const string & ln, const char & fn = "Heyyou");// #2
	// the following methods display lname and fname
	void Show() const; 		// firstname lastname format
	void FormalShow() const;// lastname, firstname format
}; 

它使用了一个 string对象和一个字符数组,让您能够比较它们的用法。请提供未定义的方法的代码,以完成这个类的实现。再编写一个使用这个类的程序,它使用了三种可能的构造函数调用(没有参数、一个参数和两个参数)以及两种显示方法。下面是一个使用这些构造函数和方法的例子:

Person one;							// use default constructor
Person two("Smythecraft");			// use #2 with one fefault argument
Person three("Dimwiddy","Sam");		// use #2, no defaults
one.Show();
cout << endl;
one.FormalShow();
//etc. for two and thre
//class.h

#ifndef _CLASS_
#define _CLASS_
#include <iostream>
#include <cstring>
class Person{
	private:
		static const int LIMIT = 25;
		std::string lname;			//Person's last name
		char fname[LIMIT];		//Person's first name
	public:
		Person() {lname = " ";fname[0] = '\0';}//#1
		Person(const std::string & ln, const char * fn = "Heyyou");// #2
	// the following methods display lname and fname
	void Show() const; 		// firstname lastname format
	void FormalShow() const;// lastname, firstname format
}; 

#endif
//class.cpp

#include "class.h"
#include <cstring>
#include <iostream>

Person::Person(const std::string & ln, const char * fn)
{
	lname = ln;
	strcpy(fname, fn);
//	fname = fn;
}

void Person::Show() const
{
	using std::cout;
	using std::endl;
	cout << "Person's first name: " << fname << endl;
	cout << "Person's last name: " << lname << endl;	
}

void Person::FormalShow() const
{
	using std::cout;
	using std::endl;
	cout << "Person's last name: " << lname << endl;
	cout << "Person's first name: " << fname << endl;	
}
//main.cpp

#include <iostream>
#include "class.h"
using namespace std;

int main()
{
	Person one;							// use default constructor
	Person two("Smythecraft");			// use #2 with one fefault argument
	Person three("Dimwiddy","Sam");		// use #2, no defaults
	one.Show();
	cout << endl;
	one.FormalShow();
	two.Show();
	cout << endl;
	two.FormalShow();
	three.Show();
	cout << endl;
	three.FormalShow();	
	return 0;
}

3.完成第9章的编程练习1,但要用正确的golf类声明替换那里的代码。用带合适参数的构造函数替换 setgolf(golf&, const char*,int),以提供初始值。保留 setgolf()的交互版本,但要用构造函数来实现它(例如, setgolf()的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象即*this)。

//golf.h

#pragma once
#ifndef _GOLF_
#define _GOLF_
const int Len = 40;
class golf {
private:
	char fullname[Len];
	int handicap;
public:
	golf(const char* name, int hc);
	int setgolf();
	void SetHandicap(int hc);
	void showgolf() const;
};

#endif // !_GOLF_

//golf.cpp

#include "golf.h"
#include <cstring>
#include <iostream>

golf::golf(const char* name, int hc)
{
	strcpy_s(fullname, name);
	handicap = hc;
}

int golf::setgolf()
{
	std::cout << "Please enter the name: ";
	std::cin.getline(fullname,Len);
	std::cout << "Please enter the handicap:";
	std::cin >> handicap;
	std::cin.get();
	golf g(fullname, handicap);
	*this = g;
	return fullname == " " ? 0 : 1;
}

void golf::SetHandicap(int hc)
{
	handicap = hc;
}

void golf::showgolf() const
{
	std::cout << "name:" << fullname << std::endl;
	std::cout << "handicap:" << handicap << std::endl;
}
//main.cpp

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

int main()
{
    golf g("Alex Tony", 10);
    g.showgolf();
    std::cout << std::endl;
    g.setgolf();
    std::cout << std::endl;
    g.showgolf();
    std::cout << std::endl;
    g.SetHandicap(99);
    g.showgolf();
    return 0;
}

4.完成第9章的编程练习4,但将 Sales结构及相关的函数转换为一个类及其方法。用构造函数替换Setsales( sales&, double[],int)函数。用构造函数实现 setsales( Sales&)方法的交互版本。将类保留在名称空间 SALES中。

//sales.h

#pragma once
#ifndef _SALES_
#define _SALES_
namespace SALES {
	const int QUARTERS = 4;
	class Sales {
	private:
		double sales[QUARTERS];
		double average;
		double max;
		double min;
	public:
		Sales();
		Sales(const double ar[], int n);
		void showSales() const;
	};
}
#endif // !_SALES_
//sales.cpp

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

SALES::Sales::Sales(const double ar[], int n)
{
	double sum = 0;
	max = ar[0];
	min = ar[0];

	for (int i = 0; i != n; i++)
	{
		sales[i] = ar[i];
		sum += ar[i];
	}
	average = sum / n;
	for (int i = 0; i != n; i++)
	{
		if (max <= ar[i])
			max = ar[i];
		if (min >= ar[i])
			min = ar[i];
	}
}

SALES::Sales::Sales()
{
	using std::cout;
	using std::cin;
	using std::endl;

	cout << "请输入不多于" << QUARTERS << "个销售金额" << endl;
	int i = 0;
	std::cout << "#1: ";
	std::cin >> sales[i];
	while (sales[i] >= 0 && i < SALES::QUARTERS)
	{
		i++;
		std::cout << "#" << i + 1 << ": ";
		std::cin >> sales[i];
		if (i == 3)
		{
			if (sales[i] < 0)
				i = i - 1;
			break;
		}
	}
	SALES::Sales sa(sales, i+1);
	*this = sa;
}

void SALES::Sales::showSales() const
{
	using std::cout;
	using std::endl;

	cout << "slaes's array of s" << endl;
	for (int i = 0; i < QUARTERS; i++)
	{
		cout << sales[i] << " ";
	}

	cout << "average: " << average << endl;
	cout << "max: " << max << endl;
	cout << "min: " << min << endl;
}
//main.cpp

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

const int ArrSize = 4;

int main()
{
    //非交互式
    std::cout << "请输入不多于" << SALES::QUARTERS << "个销售金额" << std::endl;
    double a[ArrSize];
    int i = 0;
    std::cout << "#1: ";
    std::cin >> a[i];
    while (a[i] >= 0 && i < SALES::QUARTERS)
    {
        i++;
        std::cout << "#" << i + 1 << ": ";
        std::cin >> a[i];
        if (i == 3)
        {
            if (a[i] < 0)
                i = i - 1;
            break;
        }
    }
  
    SALES::Sales s1(a, i+1);
    s1.showSales();

    //交互式
    std::cout << std::endl;
    SALES::Sales s2;
    s2.showSales();

    return 0;
}

5.考虑下面的结构声明:
struct customer {
char fullname[35];
double payment;
};
编写一个程序,它从栈中添加和删除 customer结构(栈用 Stack类声明表示).每次 customer结构被删除时,其 payment的值都被加入到总数中,并报告总数。注意:应该可以直接使用 Stack类而不作修改只需修改 typedef声明,使Item的类型为 customer,而不是 unsigned long即可。

//stack.h -- class definition for the stack ADT
#pragma once
#ifndef STACK_H_
#define STACK_H_

struct customer {
	char fullname[35];
	double payment;
};

typedef customer Item;

class Stack
{
private:
	enum {MAX = 10};
	Item items[MAX];
	int top;
	
public:
	Stack();
	bool isempty() const;
	bool isfull() const;
	bool push(const Item& item);
	bool pop(Item& item);
};
#endif
//stack.cpp -- Stack member functions
#include "stack.h"
#include <iostream>

Stack::Stack()
{
	top = 0;
}

bool Stack::isempty() const
{
	return top == 0;
}

bool Stack::isfull() const
{
	return top == MAX;
}

bool Stack::push(const Item& item)
{
	if (top < MAX)
	{
		items[top++] = item;
		return true;
	}
	else
		return false;
}

bool Stack::pop(Item& item)
{
	static double total = 0;
	if (top > 0)
	{
		item = items[--top];
		total += item.payment;
		std::cout << "total: " << total << std::endl;
		return true;
	}
	else
		return false;
}

//stacker.cpp -- testing the Stack class
#include <iostream>
#include <cctype>
#include "stack.h"

int main()
{
	using namespace std;
	Stack st;
	char ch;
	customer po;
	cout << "Please enter A to add a purchase order,\n"
		<< "P to process a PO,or Q to quit.\n";
	while (cin >> ch && toupper(ch) != 'Q')
	{
		while (cin.get() != '\n')
			continue;
		if (!isalpha(ch))//非字母响铃!!!
		{
			cout << '\a';
			continue;
		}
		switch (ch)
		{
		case 'A':
		case 'a':  cout << "Enter a PO number to add: ";
			cout << "customer's fullname: ";
			cin.getline(po.fullname,35);
			cout << "customer's payment: ";
			cin >> po.payment;
			cin.get();
			if (st.isfull())
				cout << "stack already full\n";
			else
				st.push(po);
			break;
		case 'p':
		case 'P':if (st.isempty())
			cout << "stack already empty\n";
				else {
			st.pop(po);
			cout << "customer's fullname:" << po.fullname << " popped\n";
			cout << "customer's payment:" << po.payment << " popped\n";
		}
				break;
		}
		cout << "Please enter A to ass a porchase order,\n"
			<< "P to process a PO, or Q to quit.\n";
	}
	cout << "Bye\n";
	return 0;
}

6.下面是一个类声明:

class Move{
	private:
		double x;
		double y;
	public:
		Move(double a = 0, double b = 0); 	// sets x, y to a, b
		void showmove() const;					// shows current x, y values
		Move add(const Move & m) const;
	// this function adds x of m to x of invoking object to get new x,
	// adds y of m to y of invoking object to get new y, creates a new
	// move object initialized to new x, y values and returns it
		reset(double a = 0, double b = 0);	// resets x,y to a, b
};

请提供成员函数的定义和测试这个类的程序。

//move.h
#pragma once
#ifndef MOVE_H_
#define MOVE_H_
class Move {
private:
	double x;
	double y;
public:
	Move(double a = 0, double b = 0); 	// sets x, y to a, b
	void showmove() const;					// shows current x, y values
	Move add(const Move& m) const;
	// this function adds x of m to x of invoking object to get new x,
	// adds y of m to y of invoking object to get new y, creates a new
	// move object initialized to new x, y values and returns it
	void reset(double a = 0, double b = 0);	// resets x,y to a, b
};
#endif // !MOVE_H_

//move.cpp
#include "move.h"
#include <iostream>
Move::Move(double a, double b)
{
	x = a;
	y = b;
}

void Move::showmove() const
{
	using std::cout;
	using std::endl;

	cout << "x: " << x << endl;
	cout << "y: " << y << endl;
}

Move Move::add(const Move& m) const
{
	Move mv;
	mv.x = m.x + x;
	mv.y = m.y + y;
	return mv;
}

void Move::reset(double a, double b)
{
	x = a;
	y = b;
}
//main.cpp
#include <iostream>
#include "move.h"

using namespace std;

int main()
{
	Move mv;
	mv.showmove();
	mv.reset(3, 4);
	mv.showmove();
	Move mm, ma(1, 1);
	mm = mv.add(ma);
	mm.showmove();
	return 0;
}
  1. Betelgeusean plorg有这些特征

数据:

  • long的名称不超过19个字符;
  • long有满意指数(CI),这是一个整数

操作:

  • 新的 long将有名称,其CI值为50
  • long的CI可以修改;
  • long可以报告其名称和CI
  • long的默认名称为“ Plorga”

请编写一个 Long类声明(包括数据成员和成员函数原型)来表示 long,并编写成员函数的函数定义。然后编写一个小程序,以演示 Long类的所有特性。

//plorg.h
#pragma once
#ifndef PLORG_H_
#define PLORG_H_
#include <string>

class Plorg {
private:
	std::string name;
	int CI;
public:
	Plorg(std::string na = "Plorga", int ci = 50) :name(na), CI(ci) {}
	void SetPlorg(int ci);
	void ShowPlorg() const;
};

#endif

//plorga.cpp
#include"plorg.h"
#include <iostream>
void Plorg::SetPlorg(int ci)
{
	CI = ci;
}

void Plorg::ShowPlorg() const
{
	using std::cout;
	using std::endl;

	cout << "name: " << name << endl;
	cout << "CI: " << CI << endl;
}
//main.cpp
#include"plorg.h"

int main()
{
	Plorg pl;
	pl.ShowPlorg();
	pl.SetPlorg(49);
	Plorg pp("jing liming", 23);
	pp.ShowPlorg();
	return 0;
}

8.可以将简单列表描述成下面这样:

  • 可存储0或多个某种类型的列表;
  • 可创建空列表
  • 可在列表中添加数据项
  • 可确定列表是否为空;
  • 可确定列表是否为满;
  • 可访问列表中的每一个数据项,并对它执行某种操作。
    可以看到,这个列表确实很简单,例如,它不允许插入或删除数据项。
    请设计一个List类来表示这种抽象类型。您应提供头文件 list. h和实现文件 list. cpp,前者包含类定义,后者包含类方法的实现。您还应创建一个简短的程序来使用这个类。
    该列表的规范很简单,这主要旨在简化这个编程练习。可以选择使用数组或链表来实现该列表,但公有接口不应依赖于所做的选择。也就是说,公有接口不应有数组索引、节点指针等。应使用通用概念来表达创建列表、在列表中添加数据项等操作。对于访问数据项以及执行操作,通常应使用将函数指针作为参数的函数来处理
void visit(vois (*pf) (Item &));

其中,pf指向一个将Item引用作为参数的函数(不是成员函数),Item是列表中数据项的类型。visit()函数将该函数用于列表中的每个数据项。

//头文件stock00.h  类定义
#pragma once
#ifndef STOCK00_H_
#define STOCK00_H_

typedef int Item;    //类型别名声明

class List
{
private:

	enum { MAX = 10 };
	Item items[MAX];
	int top;
public:
	List() { top = 0; }
	bool isempty() const;
	bool isfull() const;
	bool add(const Item item);
	void visit(void(*pf)(Item& item));
};

#endif
//类方法实现stock00.cpp
#include<iostream>
#include "标头.h"

bool List::isempty() const
{
	return top == 0;
}

bool List::isfull() const
{
	return top == MAX;
}

bool List::add(const Item item)
{
	if (top < MAX)
	{
		items[top++] = item;
		return true;
	}
	else
		return false;
}

void List::visit(void(*pf)(Item& item))
{
	std::cout << "\nDisplay the item:\n";
	for (int i = 0; i < top; i++)
		(*pf)(items[i]);         //显示每个item
}
//主函数usestock0.cpp
#include<iostream>
#include<string>
#include<cctype>
#include"标头.h"
using namespace std;

void func(Item& item);//函数声明

int main()
{
	List st;
	string str;
	cout << "At first:" << endl;
	if (st.isempty() == 1)
		str = "Yes!";
	if (st.isempty() == 0)
		str = "No!";
	cout << "isempty? " << str << endl;
	if (st.isfull() == 1)
		str = "Yes!";
	if (st.isfull() == 0)
		str = "No!";
	cout << "isfull? " << str << endl;
	st.add(1);
	st.add(2);
	st.add(3);
	st.add(4);
	cout << "\nNow:" << endl;
	if (st.isempty() == 1)
		str = "Yes!";
	if (st.isempty() == 0)
		str = "No!";
	cout << "isempty? " << str << endl;
	if (st.isfull() == 1)
		str = "Yes!";
	if (st.isfull() == 0)
		str = "No!";
	cout << "isfull? " << str << endl;
	void(*pf)(Item & item);
	pf = func;
	st.visit(pf);
	system("pause"); //显示暂停

	return 0;
}


void func(Item& item)
{
	cout << item << endl;
}

转载:https://blog.csdn.net/jlm7689235/article/details/105650231
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场