(2)风色从零单排《C++ Primer》 一个简单的书店程序

来源:互联网 发布:冷血动物认主人吗 知乎 编辑:程序博客网 时间:2024/04/29 05:57

从零单排《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.99std::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目录下。


0 0