设为首页 加入收藏

TOP

1.5 Introducing Classes (3)
2013-10-07 16:14:43 来源: 作者: 【 】 浏览:80
Tags:1.5 Introducing Classes

KEY CONCEPT: CLASSES DEFINE BEHAVIOR

The important thing to keep in mind when you read these programs is that the author of the Sales_item class defines all the actions that can be performed by objects of this class. That is, the Sales_item class defines what happens when a Sales_item object is created and what happens when the assignment, addition, or the input and output operators are applied to Sales_items.

In general, the class author determines all the operations that can be used on objects of the class type. For now, the only operations we know we can perform on Sales_item objects are the ones listed in this section.
Reading and Writing Sales items

Now that we know what operations we can use with Sales_item objects, we can write programs that use the class. For example, the following program reads data from the standard input into a Sales_item object and writes that Sales_item back onto the standard output:

  1. #include <iostream>   
  2. #include "Sales_item.h"   
  3. int main()   
  4. {   
  5. Sales_item book;   
  6. // read ISBN, number of copies sold, and sales price   
  7. std::cin >> book;   
  8. // write ISBN, number of copies sold, total revenue, and average price   
  9. std::cout << book << std::endl;   
  10. return 0;   
  11. }  

If the input to this program is

  1. 0-201-70353-X 4 24.99  

then the output will be

  1. 0-201-70353-X 4 99.96 24.99 

Our input says that we sold four copies of the book at $24.99 each, and the output indicates that the total sold was four, the total revenuewas $99.96, and the average price per book was $24.99.

This program starts with two #include directives, one of which uses a new form. Headers from the standard library are enclosed in angle brackets (< >). Those that are not part of the library are enclosed in double quotes (" ").

Inside main we define an object, named book, that we’ll use to hold the data that we read from the standard input. The next statement reads into that object, and the third statement prints it to the standard output followed by printing endl.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.4 Flow of Control (7) 下一篇1.5 Introducing Classes (5)

评论

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

·数据库:推荐几款 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)