我这本教材上没有相关例题。。。我自己编了一个类的程序,麻烦您把详细操作过程告诉我,非常谢谢。
class cashregister
{
public:
int getcurrentbalance() const;
void acceptamount(int amount);
cashregister(int cashin=500);
private:
int cashonhand;
};
class dispensertype
{
public:
int getnoofitems() const;
int getcost() const;
void makesale();
dispensertype(int setnoofitems=50, int setcost=50);
private:
int numberofitems;
int cost;
};
#include <iostream>
#include "cashregister.h"
using namespace std;
int cashregister::getcurrentbalance() const
{
return cashonhand;
}
void cashregister::acceptamount(int amount)
{
cashonhand+=amount;
}
cashregister::cashregister(int cashin)
{
if(cashin>=0)
cashonhand=cashin;
else
cashonhand=500;
}
#include <iostream>
#include "dispensertype.h"
using namespace std;
int dispensertype::getnoofitems() const
{
return numberofitems;
}
int dispensertype::getcost() const
{
return cost;
}
void dispensertype::makesale()
{
numberofitems--;
}
dispensertype::dispensertype(int setnoofitems, int setcost)
{
if(setnoofitems>=0)
numberofitems=setnoofitems;
else
numberofitems=50;
if(setcost>=0)
cost=setcost;
else
cost=50;
}
#include <iostream>
#include "cashregister.h"
#include "dispensertype.h"
using namespace std;
void showselection();
void sellproduct(dispensertype& produce, cashregister& pcounter);
int main()
{
cashregister counter;
dispensertype candy(100,50);
dispensertype chips(100,65);
dispensertype gum(75,45);
dispensertype cookies(100, 85);
int choice;
showselection();
cin>>choice;
while(choice!=9)
{
switch(choice)
{
case 1: sellproduct(candy, counter);break;
case 2: sellproduct(chips, counter);break;
case 3: sellproduct(gum, counter);break;
case 4: sellproduct(cookies, counter);break;
default: cout<<"invalid selection."<<endl;
}
showselection();
cin>>choice;
}
return 0;
}
void showselection()
{
cout<<"***welcome to shelly's candy shop***"<<endl;
cout<<"TO select an item, enter"<<endl;
cout<<"1 for candy"<<endl;
cout<<"2 for chips"<<endl;
cout<<"3 for gum"<<endl;
cout<<"4 for cookies"<<endl;
cout<<"9 to exit"<<endl;
}
void sellproduct(dispensertype& product, cashregister& pcounter)
{
int amount1;
int amount2;
if(product.getnoofitems()>0)
{
cout<<"please deposit "<<product.getcost()<<"cents"<<endl;
cin>>amount1;
if(amount1<product.getcost())
{
cout<<"please deposit another"<<product.getcost()-amount1<<"cents"<<endl;
cin>>amount2;
amount1+=amount2;
}
if(amount1>=product.getcost())
{
pcounter.acceptamount(amount1);
product.makesale();
cout<<"collect your item at the bottom and enjoy."<<endl;
}
else
cout<<"the amount is not enough."<<"collect what you deposited."<<endl;
cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-"<<endl;
cout<<endl;
}
else
cout<<"sorry, this item is sold out"<<endl;
}