C++ Primer Section 1-5

Section 1-5 Introducing Class

Sales_item Class

A class in C++ is a data structure, a type.

When we look at a class, we should focus on the legal operations of it and not bother to care about the implement of these operations.

Operations On Sales_item

  • Function named isbn to fetch the ISBN from a Sales_item object.

  • << and >> operators to read and write objects of type Sales_item

  • = to assign one Sales_item object to another

  • + to add two Sales_item objects with the same ISBN, producing a new Sales_item object with the same ISBN, the sum of the copies they are sold and the total revenue they made

  • += to add one Sales_item to another

They must overload the operator <<, >>, +, +=.

Exercises

Exercises 1-20

http://www.informit.com/title/032174113 contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that file to your working directory. Use it to write a program that reads a set of book sales transactions, writing each transaction to the standard output.

Solution

In 1-20.cpp

Exercise 1-21

Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.

Solution

In Example Code/Add.cpp

Exercise 1-22

Write a program that reads several transactions for the same ISBN. Write the sum of all the transactions that were read.

Solution

In 1-22.cpp

A First Look at Member Function

Member Functions, also referred as Methods.

To access a member function, we use dot operator . , like item1.isbn. But if we want to call a member function, we need the call operator (), like item1.isbn(). All the arguments(maybe none) shall be included in the parentheses.

Exercises

Exercise 1-23

Write a program that reads several transactions and counts how many transactions occur for each ISBN.

Solution

In 1-23.cpp

According to the description of input file in Exercise 1-24, we know that this program is like the IfStatement.cpp in Section 1-4.

Exercises 1-24

Test the previous program by giving multiple transactions representing multiple ISBNs. The records for each ISBN should be grouped together.

Using File Redirection

$./Add out

It means that the executable program Add will read from file in and write to file out.

In Linux system, you can use >> to redirect the writing object without erasing previous contents.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值