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.