第十章 编程练习
1.为复习题5描述的类提供方法定义,并编写一个小程序来演示所有的特性。
头文件(类定义):
#ifndef Account_H_
#define Account_H_
//#include<iostream>
#include<string>
using namespace std;
class BankAccount
{
private:
string name;
string account;
double balance;
public:
BankAccount();
BankAccount(const string & client,const string num,double bal=0.0);
~BankAccount();
void show() const;
void save(double cash);
void expend(double cash);
};
#endif
源文件(方法定义):
#include<iostream>
#include"Account.h"
using namespace std;
BankAccount::BankAccount()
{
name = "no name";
account ="no account";
balance = 0.0;
}
BankAccount::BankAccount(const string & client,const string num,double bal)
{
name = client;
account = num;
if (bal<0)
{
cout<<"You have no balance."<<endl;
balance =0;
}
else
balance = bal;
}
BankAccount::~BankAccount()
{
cout<<"Bye,Irregular variable..."<<endl;
}
void BankAccount::show() const
{
cout<<"Now bankaccount..."<<endl;
cout<<"BankAccount.name is "<<name<<endl;
cout<<"BankAccount.account is "<<account<<endl;
cout<<"BankAccount.balance is "<<balance<<endl;
}
void BankAccount::save(double cash)
{
balance +=cash;
}
void BankAccount::expend(double cash)
{
balance -=cash;
}
测试文件:
#include<iostream>
#include"Account.h"
using namespace std;
int main()
{
{
cout<<"Using constructors to create new objects:\n";
BankAccount account1=BankAccount();
account1.show();
BankAccount account2("樊一超","fanacio",900);
account2.show();
account1.save(200);
account1.show();
account2.expend(900);
account2.show();
account1 = BankAccount("fanacio","zjut_bank_card",21000);
account1.show();
cin.get();
cout<<"Done........\n";
}
return 0;
}
运行结果:
2.
头文件(类定义):
//person.h --使用string对象和一个字符数组,然后扯淡的比较了他俩的用法,真TM无聊。
#ifndef PERSON_H_
#define RENSON_H_
#include<string>
using namespace std;
class Person
{
private:
static const int LIMIT = 25;
string lname;
char fname[LIMIT];
public:
Person(){lname="";fname[0]='\0'; }
Person(const string & ln,const char * fn = "Heyyou");
void Show()const;
void FormalShow() const;
};
#endif
源函数文件(方法描述):
#include<iostream>
#include"person.h"
using namespace std;
Person::Person(const string & ln,const char * fn )
{
lname=ln;
strcpy(fname,fn);
}
void Person::Show()const
{
cout<<"firstname lastname format..."<<endl;
cout<<fname<<" "<<lname<<endl;
}
void Person::FormalShow() const
{
cout<<"lastname,firstname format..."<<endl;
cout<<lname<<" , "<<fname<<endl;
}
源函数(测试文件):
#include<iostream>
#include"person.h"
using namespace std;
int main()
{
Person one;
Person two("Smythecreft");
Person three("Dimwiddy","Sam");
one.Show();
cout<<endl;
one.FormalShow();
cout<<endl;
two.Show();
cout<<endl;
two.FormalShow();
cout<<endl;
three.Show();
cout<<endl;
three.FormalShow();
cout<<endl;
cin.get();
return 0;
}
运行结果:
3.对第9章编程练习1进行修改,应用类定义。
头文件(类定义):
//golf.h --使用正确的类声明,使用合适的构造函数,以提供初始值。
#ifndef GOLF_H_
#define GOLF_H_
class golf
{
private:
static const int Len = 40;
char fullname[Len];
int handicap;
public:
//non-interactive version:
// function sets golf structure to provided name,handicap
// using values passed as arguments to the function
golf();
golf(const char * name,int hc);
~golf();
void hand(int hc);
void showgolf() const;
};
#endif
源函数(方法定义):
//golf.cpp --匹配头文件中的原型函数
#include<iostream>
#include<string>
#include"golf.h"
golf::golf()
{
std::cout<<"Default constructor called\n";
char name[Len];
int hc;
std::cout<<"请输入姓名:";
std::cin.getline(name,Len);
std::cout<<"请输入等级:";
std::cin>>hc;
std::cin.get();
*this =golf(name,hc);
}
golf::golf(const char * name,int hc)
{
strcpy(fullname,name);
handicap = hc;
}
golf::~golf()
{
std::cout<<"Bye,Temporary variables...\n";
}
void golf::hand(int hc)
{
handicap = hc;
}
void golf::showgolf()const
{
using namespace std;
cout<<"姓名:\t"<<fullname<<endl;
cout<<"等级:\t"<<handicap<<endl;
}
源函数(测试文件):
//main()演示原型化函数的所有特性。例如,包含一个让用户输入循环,并使用输入的数据来填充一个由golf结构组成的数组,
//数组被填满或用户将高尔夫选手的姓名设置为空字符串时,循环将结束。
//main()函数只使用头文件中原型化的函数来访问golf结构。
#include<iostream>
#include"golf.h"
using namespace std;
int main()
{
golf g0;
g0.showgolf();
g0.hand(120);
g0.showgolf();
golf g1("Jimmy", 100);
g1.showgolf();
g1.hand(120);
g1.showgolf();
return 0;
}
运行结果:
4.对第9章编程练习4进行修改,应用类定义。
头文件(类定义和声明):
//将第9章编程练习4的Sales结构及相关的函数转换为一个类及其方法。
#ifndef SALES_H_
#define SALES_H_
namespace SALES
{
const int QUARTERS = 4;
const double init_ar[4] = {0.0, 0.0, 0.0, 0.0};
class sales
{
private:
double salesfan[QUARTERS];
double average;
double max;
double min;
public:
sales(const double ar[]=init_ar,int n=4);
void setSales();
void showSales() const;
};
}
#endif
方法定义文件:
//对名称空间进行扩展,以提供这三个函数的定义
#include<iostream>
#include"sales.h"
using namespace std;
namespace SALES
{
sales::sales(const double ar[],int n)
{
if(n<4)
{
for (int i=0;i<n;i++)
salesfan[i]=ar[i];
for (int j=n;j<4;j++)
salesfan[j]=0;
}
else
{
for (int i=0;i<4;i++)
salesfan[i]=ar[i];
}
average=(salesfan[0]+salesfan[1]+salesfan[2]+salesfan[3])/QUARTERS;
double max0=salesfan[0];
for (int i=1;i<QUARTERS;i++)
{
if (max0<salesfan[i])
max0=salesfan[i];
}
max=max0;
double min0=salesfan[0];
for (int i=1;i<QUARTERS;i++)
{
if (min0>salesfan[i])
min0=salesfan[i];
}
min=min0;
}
void sales::setSales()
{
double input[QUARTERS];
for(int i=0;i<QUARTERS;i++)
{
cout<<"请输入第"<<i+1<<"季度的销售额:";
cin>>input[i];
cin.get();
}
*this = sales(input,QUARTERS);
}
void sales::showSales() const
{
cout<<"display all information in structure s:\n";
for (int i=0;i<QUARTERS;i++)
cout<<"the "<<i+1<<"quarters is "<<salesfan[i]<<endl;
cout<<endl<<"the average:\t"<<average<<endl;
cout<<"the max:\t"<<max<<endl;
cout<<"the min:\t"<<min<<endl;
}
}
测试文件:
//声明两个Sales对象,并使用setSales()的交互式版本为一个结构提供值,然后使用setSales()的非交互式版本为另一个结构提供值。
//使用showSales()来显示这两个结构的内容。
#include<iostream>
#include"sales.h"
using namespace std;
using namespace SALES;
int main()
{
double ar1[4] = {1,2,3,4};
double ar2[3] = {12.5,55.2,60.7};
sales object1;
sales object2 = sales(ar1,4);
sales object3(ar2,3);
cout<<"The following is the first sales' information:\n";
object1.showSales();
cout<<endl<<"The following is the second sales' information:\n";
object2.showSales();
cout<<endl<<"The following is the tired sales' information:\n";
object3.showSales();
cout<<endl;
cout<<endl<<"The following is the first sales' alter information:\n";
object1.setSales();
object1.showSales();
cin.get();
return 0;
}
运行结果:
5.一个类似于程序清单10.10-1.12的练习。
类定义和声明头文件:
//Stack.h --class definition for the stack ADT
#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 --对头文件函数成员的解释.
#include"Stack.h"
Stack::Stack() // create an empty 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)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
测试文件:
//usestack.cpp --testing the Stack class
#include <iostream>
#include <cctype> // or ctype.h
#include "stack.h"
int main()
{
using namespace std;
Stack st; // create an empty stack
char ch;
customer po;
double sumpayment=0;
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 the fullname of PO: ";
cin.getline(po.fullname,35);
cout << "Enter the payment of PO: ";
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 << "PO #" << po.fullname << " popped\n";
sumpayment += po.payment;
}
break;
}
cout << "Please enter A to add a purchase order,\n"
<< "P to process a PO, or Q to quit.\n";
}
cout << "Bye\n";
cout << "Service end.\nThe total payment is " << sumpayment << endl;
cin.get();
system("pause");
return 0;
}
运行结果:
6.涉及到两个对象同时访问的一个例子
类定义和声明的头文件
//move.h
#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;
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 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.cpp --定义成员函数
#include<iostream>
#include"move.h"
Move::Move(double a,double b)
{
x=a;
y=b;
}
void Move::showmove() const
{
std::cout<<"x = \t"<<x<<std::endl;
std::cout<<"y = \t"<<y<<std::endl;
}
Move Move::add (const Move & m) const //涉及到对象的比较
{
Move newone;
newone.x=x+m.x;
newone.y=y+m.y;
return newone;
}
void Move::reset(double a,double b)
{
x=a;
y=b;
}
测试文件:
//usemove.cpp --测试程序.
#include<iostream>
#include"move.h"
using namespace std;
int main()
{
Move move1;
move1.showmove();
move1.reset(1,2);
move1.showmove();
Move move2=Move(2,3);
//move2.showmove();
//move2.reset();
move2.showmove();
Move move3=move1.add(move2);
move3.showmove();
cin.get();
return 0;
}
运行结果:
7.Betelgeusean plorg类的表示
类定义和声明头文件:
//Betelgeusean plorg.h --该类的特征.
#ifndef PLORG_H_
#define PLORG_H_
class plorg
{
private:
char name[20];
int CI;
public:
plorg();
plorg(const char name1[],int n=50);
int alter_CI(void);
void show();
};
#endif
类方法描述源文件:
//Betelgeusean plorg.cpp --对函数成员的描述.
#include<iostream>
#include<string>
#include"Betelgeusean plorg.h"
using namespace std;
plorg::plorg()
{
strcpy( name,"Plorga");
CI=50;
};
plorg::plorg(const char name1[],int n)
{
strcpy(name,name1);
CI = n;
}
int plorg::alter_CI(void)
{
int m;
cout<<"enter new CI:";
cin>>m;
CI=m;
return CI;
}
void plorg::show()
{
cout<<"name-->"<<name<<" ; "<<" CI-->"<<CI<<"..."<<endl;
}
测试文件:
//useBetelgeusean_plorg.cpp --测试
#include<iostream>
#include"Betelgeusean plorg.h"
using namespace std;
int main()
{
plorg plorg1;
plorg1.show();
plorg1 = plorg("name1");
plorg1.show();
plorg plorg2("name2", 500);
plorg2.show();
plorg1.alter_CI();
plorg1.show();
cin.get();
cin.get();
return 0;
}
运行结果:
8.类定义和声明的头文件:
//List.h --类定义.
#ifndef LIST_H_
#define LIST_H_
typedef int Item;
class list
{
private:
enum {MAX = 10};
Item items[MAX];
int top;
public:
list();
bool isempty() const;
bool isfull() const;
bool push(const Item & item);
void visit(void(*pf)(Item & ));
void showitem() const;
};
void plus100(Item & item);
#endif
类方法描述源文件:
//List.cpp --定义函数成员
#include<iostream>
#include"List.h"
list::list()
{
top =0;
}
bool list::isempty()const
{
return top ==0;
}
bool list::isfull()const
{
return top ==MAX;
}
bool list::push(const Item & item)
{
if (top<MAX)
{
items[top++]=item;
return true;
}
else
return false;
}
void list::visit(void(*pf)(Item & ))
{
for(int i=0;i<top;i++)
pf(items[i]);
}
void list::showitem() const
{
for(int i=0;i<top;i++)
std::cout<<"#"<<i+1<<": "<<items[i]<<std::endl;
}
void plus100(Item & item)
{
item += 100;
}
测试文件:
//uselist.cpp --测试.
#include<iostream>
#include<cctype>
#include"List.h"
int main()
{
using namespace std;
list lt;
char ch;
int data;
cout<<"Please enter C to create your list,P to process the list,S to show the items, Q to quit:\n";
while(cin>>ch && toupper(ch)!='Q')
{
while(cin.get()!='\n')
continue;
if (!isalpha(ch))
{
cout<<'\a';
continue;
}
switch(ch)
{
case 'C':
case 'a':cout<<"Enter C to create your list,\n";
if(lt.isfull())
cout << "The list already full.\n";
else
{
cout << "Enter the data: ";
cin>>data;
lt.push(data);
}
break;
case 'P':
case 'p':cout<<" P to process the list, \n";
if(lt.isempty())
cout<<"the list already empty\n";
else
{
lt.visit(plus100);
cout<<"Every data has plused 100.\n";
}
break;
case 'S':
case 's':cout<<"S to show the items, Q to quit:\n";
lt.showitem();
break;
}
cout<<"Please enter C to create your list,P to process the list,S to show the items, Q to quit:\n";
}
lt.showitem();
cout << "Bye!\n";
cin.get();
cin.get();
return 0;
}
运行结果: