Adding Sales items
A more interesting example adds two Sales item objects:
- #include <iostream>
- #include "Sales_item.h"
- int main()
- {
- Sales_item item1, item2;
- std::cin >> item1 >> item2;
- std::cout << item1 + item2 << std::endl;
- return 0;
- }
If we give this program the following input
- 0-201-78345-X 3 20.00
- 0-201-78345-X 2 25.00
our output is
- 0-201-78345-X 5 110 22
This program starts by including the Sales_item and iostream headers. Next we define two Sales_item objects to hold the transactions. We read data into these objects fromthe standard input. The output expression does the addition and prints the result.
It’s worth noting how similar this program looks to the one on page 6: We read two inputs and write their sum. What makes this similarity noteworthy is that instead of reading and printing the sum of two integers, we’re reading and printing the sum of two Sales_item objects. Moreover, the whole idea of “sum” is different. In the case of ints we are generating a conventional sum—the result of adding two numeric values. In the case of Sales_item objects we use a conceptually new meaning for sum—the result of adding the components of two Sales_item objects.