從零單排《C++ Primer》
——(2)一個簡單的書店程序
0、寫在前面
這個章節將會體驗類(class)的使用,實現一個簡單的書店程序。在之後的章節,我們纔會學習類的更多細節,如如何自己實現一個類。
1、什麼是類
在c++中,我們使用類來定義自己的數據結構。類定義了一種類型,包含和該類型相關的操作。我們通過頭文件來訪問那些已經被定義的類。通常,頭文件的名稱來源於頭文件內的類名。我們自己實現的頭文件通常跟着後綴.h。而標準庫的文件通暢則是沒有後綴的。
#include <iostream>
#include "Sales_item.h"
int main()
{
Sakes_item item1,item2;
std::cin>>item1 >> item2;
if(item1.isbn() == item2.isbn()){
std::count<<item1 + item2 <<std::endl;
return 0; //indicate success 表明成功
}else{
std::cerr << "Data must refer to same ISBN" <<std::endl;
return -1; //indicate failure 表明失敗
}
}
在這個程序中,我們首先引入了來自標準庫的頭文件iostream和別人寫好的Sales_item.h。Sales_item類用來儲存一條銷售記錄的相關信息,如書本的ISBN號。每一個類都定義了一種類型,在這裏,Sales_item類定義了一種Sales_item類型。
2、類的成員函數
在上面的程序中,item1.isbn() == item2.isbn()執行了函數名爲isbn的成員函數。成員函數是類中定義的函數。通常,我們把成員函數稱作類對象的行爲。使用操作符"."來訪問類的成員。在這裏,item1.isbn()函數返回儲存在item1內的ISBN號。
3、一個簡單的書店程序
程序意圖:在終端上輸入一組書店銷售記錄,輸出每本書的銷售總額
代碼:
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item total; //variable to hold data for the next transaction 儲存下一條銷售記錄
//read the first transaction and ensure that there are data to process 讀取第一條銷售記錄,以保證有數據可操作
//讀取ISBN,銷售數量,每本的價格 如0-201-70353-X 4 24.99
if(std::cin>>total){
Sales_item trans;// variable to hold the running sum //正在處理的記錄
while(std::cin>>trans){
// if we're still processing the same book //如果是同一本書的記錄
if(total.isbn() == trans.isbn())
total += trans;// update the running total更新總額
else{
// print result for the previous book 打印上一本書的計算結果
// 打印ISBN,銷售數目,銷售總額,平均每本書價格 如0-201-70353-X 4 99.96 24.99
std::cout<<total<<std::endl;
total = trans;
}// total now refers to the next book 指向下一本書
}
std::cout<<total<<std::endl;//print the last transaction 打印最後一條記錄
}else{
// no input!warn the user 沒有數據,向用戶發出警告
std::cerr<<"No data?!"<<std::endl;
return -1;
}
}
在這裏(點擊打開鏈接)可以下載到書本的源代碼。Sales_item.h在Chapter 1 code directory目錄下。