设为首页 加入收藏

TOP

1.5 Introducing Classes (4)
2013-10-07 16:14:35 来源: 作者: 【 】 浏览:66
Tags:1.5 Introducing Classes

Adding Sales items

A more interesting example adds two Sales item objects:

  1. #include <iostream>   
  2. #include "Sales_item.h"   
  3. int main()   
  4. {   
  5. Sales_item item1, item2;   
  6. std::cin >> item1 >> item2; // read a pair of transactions   
  7. std::cout << item1 + item2 << std::endl; // print their sum   
  8. return 0;   
  9. }  


If we give this program the following input

  1. 0-201-78345-X 3 20.00   
  2. 0-201-78345-X 2 25.00  

our output is

  1. 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.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.5 Introducing Classes (5) 下一篇1.6 The Bookstore Program (1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·数据库:推荐几款 Re (2025-12-25 12:17:11)
·如何最简单、通俗地 (2025-12-25 12:17:09)
·什么是Redis?为什么 (2025-12-25 12:17:06)
·对于一个想入坑Linux (2025-12-25 11:49:07)
·Linux 怎么读? (2025-12-25 11:49:04)