NO IMAGE

今天一上午用類做了一個自動販賣機的程式需要.h標頭檔案和.cpp原始檔。原始碼如下

//candy Machine Header File
#ifndef ITEM_BASE//為避免類重複定義,需要在標頭檔案的開頭和結尾加上如這個所示
#define ITEM_BASE
class cashRegister
{
public:
int getCurrentBalance() const;
//該函式來顯示當前的現金,返回收鈔口的值
void acceptAmount(int amountIn);
//接受顧客的錢並更新當前的現金值
cashRegister(int cashIn=500);
//將總現金設定為特定的值,若沒有輸入值,則預設為500;
private:
int cashOnHand;
};
class dispenserType
{
public:
int getNoOfItems() const;
//展示機器中某商品的數量
int getCost() const;
//展示某商品的價格
void makeSale();
//減少機器中的商品數量
dispenserType(int setNoOfItems=50,int setCost=50);
//將貨架上商品的數量和價格設定為特定的值,若沒有值輸入則設定為預設50,50
private:
int numberOfItems;//儲存貨架上商品的數量
int cost;//儲存商品的價格
};
#endif

下面是原始檔

#include<iostream>
#include"candyMachine.h"
using namespace std;
int cashRegister::getCurrentBalance()const
{
return cashOnHand;
}
void cashRegister::acceptAmount(int amountIn)
{
cashOnHand =amountIn;
}
cashRegister::cashRegister(int cashIn)
{
if(cashIn>=0)
cashOnHand=cashIn;
else
cashOnHand=500;
}
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"candyMachine.h"
using namespace std;
void showSelection();
void sellProduct(dispenserType& product,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<<"Invaild selection."<<endl;
}
showSelection();
cin>>choice;
}
return 0;
}
void showSelection()
{
cout<<"***Welcome to diyhoo'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 for exit"<<endl;
}
void sellProduct(dispenserType& product,cashRegister& pCounter)
{
int amount;
int amount2;
if(product.getNoOfItems()>0)
{
cout<<"Please deposit"<<product.getCost()<<"cents"<<endl;
cin>>amount;
if(amount<product.getCost())
{
cout<<"Please deposit another"<<product.getCost()-amount<<"cents"<<endl;
cin>>amount2;
amount =amount2;
}
if(amount>=product.getCost())
{
pCounter.acceptAmount(amount);
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<<endl;
}
else
cout<<"sorry,this item is sold out."<<endl;
}