




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、装订线安徽工业大学 毕业设计(论文)说明书共 13 页 第 PAGE 13 页英文翻译英语原文:. Introducing Classes The only remaining feature we need to understand before solving our bookstore problem is how to write a data structure to represent our transaction data. In C+ we define our own data structure by defining a class. The class mechan
2、ism is one of the most important features in C+. In fact, a primary focus of the design of C+ is to make it possible to define class types that behave as naturally as the built-in types themselves. The library types that weve seen already, such as istream and ostream, are all defined as classesthat
3、is,they are not strictly speaking part of the language. Complete understanding of the class mechanism requires mastering a lot of information. Fortunately, it is possible to use a class that someone else has written without knowing how to define a class ourselves. In this section, well describe a si
4、mple class that we canuse in solving our bookstore problem. Well implement this class in the subsequent chapters as we learn more about types,expressions, statements, and functionsall of which are used in defining classes. To use a class we need to know three things: What is its name? Where is it de
5、fined? What operations does it support? For our bookstore problem, well assume that the class is named Sales_item and that it is defined in a header named Sales_item.h. The Sales_item Class The purpose of the Sales_item class is to store an ISBN and keep track of the number of copies sold, the reven
6、ue, and average sales price for that book. How these data are stored or computed is not our concern. To use a class, we need not know anything about how it is implemented. Instead, what we need to know is what operations the class provides. As weve seen, when we use library facilities such as IO, we
7、 must include the associated headers. Similarly, for our own classes, we must make the definitions associated with the class available to the compiler. We do so in much the same way. Typically, we put the class definition into a file. Any program that wants to use our class must include that file. C
8、onventionally, class types are stored in a file with a name that, like the name of a program source file, has two parts: a file name and a file suffix. Usually the file name is the same as the class defined in the header. The suffix usually is .h, but some programmers use .H, .hpp, or .hxx. Compiler
9、s usually arent picky about header file names, but IDEs sometimes are. Well assume that our class is defined in a file named Sales_item.h. Operations on Sales_item Objects Every class defines a type. The type name is the same as the name of the class. Hence, our Sales_item class defines a type named
10、Sales_item. As with the built-in types, we can define a variable of a class type. When we write Sales_item item we are saying that item is an object of type Sales_item. We often contract the phrase an object of type Sales_item toaSales_ item object or even more simply to a Sales_item. In addition to
11、 being able to define variables of type Sales_item, we can perform the following operations on Sales_item objects: Use the addition operator, +, to add two Sales_items, Use the input operator, to write a Sales_item object, Use the assignment operator, =, to assign one Sales_item object to another, C
12、all the same_isbn function to determine if two Sales_items refer to the same book. Classes are central to most C+ programs: Classes let us define our own types that are customizedfor the problems we need to solve, resulting in applications that are easier to write and understand.Well-designed class
13、types can be as easy to use as the built-in types. A class defines data and function members: The data members store the state associated with objectsof the class type, and the functions perform operations that give meaning to the data. Classeslet us separate implementation and interface. The interf
14、ace specifies the operations that the classsupports. Only the implementor of the class need know or care about the details of the implementation. This separation reduces the bookkeeping aspects that make programming tedious anderror-prone. Class types often are referred to as abstract data types. An
15、 abstract data type treats the data(state) and operations on that state as a single unit. We can think abstractly about what the classd oes, rather than always having to be aware of how the class operates. Abstract data types arefundamental to both object-oriented and generic programming. Data abstr
16、action is a programming (and design) technique that relies on the separation of interfaceand implementation. The class designer must worry about how a class is implemented, but programmersthat use the class need not know about these details. Instead, programmers who use a type need to know only the
17、types interface; they can think abstractly about what the type does rather than concretely about how the type works. Encapsulation is a term that describes the technique of combining lower-level elements to forma new, higher-level entity. A function is one form of encapsulation: The detailed actions
18、 performedby the function are encapsulated in the larger entity that is the function itself. Encapsulated elements hide the details of their implementationwe may call a function but have no access to the statements that it executes. In the same way, a class is an encapsulated entity: It represents a
19、n aggregation of several members, and most (well-designed) class types hide the members that implement the type. If we think about the library vector type, it is an example of both data abstraction and encapsulation. It is abstract in that to use it, we think about its interfaceabout the operations
20、that it can perform. It is encapsulated because we have no access to the details of how the type is representated nor to any of its implementation artifacts. An array, on the other hand, is similar in concept to a vector but is neither abstract nor encapsulated. We manipulate an array directly by ac
21、cessing the memory in which the array is stored. Not all types need to be abstract. The library pair class is a good example of a useful, well-designed class that is concrete rather than abstract. A concrete class is a class that exposes, rather than hides, its implementation. Some classes, such as
22、pair, really have no abstract interface. The pair type exists to bundle two data members into a single object. There is no need or advantage to hiding the data members. Hiding the members in a class like pair would only complicate the use of the type. Even so, such types often have member functions.
23、 In particular, it is a good idea for any class that has data members of built-in or compound type to define constructor(s) to initialize those members. The user of the class could initialize or assign to the data members but it is less error-prone for the class to do so. Programmers tend to think a
24、bout the people who will run their applications as users. Applicationsare designed for and evolve in response to feedback from those who ultimately use the applications. Classes are thought of in a similar way: A class designer designs and implements a class for users of that class. In this case, th
25、e user is a programmer, not the ultimate user of the application. Authors of successful applications do a good job of understanding and implementing the needs ofthe applications users. Similarly, well-designed, useful classes are designed with a close attention to the needs of the users of the class
26、. In another way, the division between class designer and class user reflects the division betweenusers of an application and the designers and implementors of the application. Users care only if the application meets their needs in a cost-effective way. Similarly, users of a class care only about i
27、ts interface. Good class designers define a class interface that is intuitive and easy to use. Users care about the implementation only in so far as the implementation affects their use of the class. If the implementation is too slow or puts burdens on users of the class, then the users must care. I
28、n well-designed classes, only the class designer worries about the implementation. In simple applications, the user of a class and the designer of the class might be one and the same person. Even in such cases, it is useful to keep the roles distinct. When designing the interface to a class, the cla
29、ss designer should think about how easy it will be to use the class. When using the class, the designer shouldnt think about how the class works. When referring to a user, the context makes it clear which kind of user is meant. If we speak of user code or the user of the Sales_item class, we mean a
30、programmer who is using a class in writing an application. If we speak of the user of the bookstore application, we mean the manager of the store who is running the application. Data abstraction and encapsulation provide two important advantages: 1.Class internals are protected from inadvertent user
31、-level errors, which might corrupt the state of the object. 2.The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code. By defining data members only in the private section of the class, the class author is free to
32、make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data are public, then any function that directly accesses the data members of the old representation might be broken. It would be necessary to locate and rewri
33、te all those portions of code that relied on the old pesentation before the program could be used again. Similarly, if the internal state of the class is private, then changes to the member data can happen in only a limited number of places. The data is protected from mistakes that users might intro
34、duce. If there is a bug that corrupts the objects state, the places to look for the bug are localized: When data are private, only a member function could be responsible for the error. The search for the mistake is limited, greatly easing the problems of maintenance and program correctness. If the d
35、ata are private and if the interface to the member functions does not change, then user functions that manipulate class objects require no change. Because changing a class definition in a header file effectively changes the text of every source file that includes that header, code that uses a class
36、must be recompiled when the class changes. Classes are the most fundamental feature in C+. Classes let us define new types that are tailored to our own applications, making our programs shorter and easier to modify. Data abstractionthe ability to define both data and function membersand encapsulatio
37、nthe ability to protect class members from general accessare fundamental to classes. Member functions define the interface to the class. We encapsulate the class by making the data and functions used by the implementation of a class private. Classes may define constructors, which are special member
38、functions that control how objects of the class are initialized. Constructors may be verloaded. Every constructor should initialize every data member. Constructors should use a constructor initializer list to initialize the data members. Initializer lists are lists of namevalue pairs where the name
39、is a member and the value is an initial value for that member. Classes may grant access to their nonpublic members to other classes or functions. A class grants access by making the class or function a friend. Classes may also define mutable or static members. A mutable member is a data member that
40、is never const; its value may be changed inside a const member function. A static member can be either function or data; static members exist independently of the objects of the class type.Copy Control Each type, whether a built-in or class type, defines the meaning of a (possibly empty) set of oper
41、ations on objects of that type. We can add two int values, run size on a vector, and so on. These operations define what can be done with objects of the given type. Each type also defines what happens when objects of the type are created. Initialization of objects of class type is defined by constru
42、ctors. Types also control what happens when objects of the type are copied, assigned, or destroyed. Classes control these actions through special member functions: the copy constructor, the assignment operator, and the destructor. This chapter covers these operations. When we define a new type, we s
43、pecifyexplicitly or implicitlywhat happens when objects of that type are copied, assigned, and destroyed. We do so by defining special members: the copy constructor, the assignment operator, and the destructor. If we do not explicitly define the copy constructor or the assignment operator, the compi
44、ler will (usually) define them for us. The copy constructor is a special constructor that has a single parameter that is a (usually const) reference to the class type. The copy constructor is used explicitly when we define a new object and initialize it from an object of the same type. It is used im
45、plicitly when we pass or return objects of that type to or from functions. Collectively, the copy constructor, assignment operator, and destructor are referred to as copy control. The compiler automatically implements these operations, but the class may define its own versions. Copy control is an es
46、sential part of defining any C+ class. Programmers new to C+ are often confused by having to define what happens when objects are copied, assigned, or destroyed. This confusion is compounded because if we do not explicitly define these operations, the compiler defines them for usalthough they might
47、not behave as we intend. Often the compiler-synthesized copy-control functions are finethey do exactly the work that needs to be done. But for some classes, relying on the default definitions leads to disaster. Frequently,the most difficult part of implementing the copy-control operations is recogni
48、zing when we need to override the default versions. One especially common case that requires the class to define its own the copy-control members is if the class has a pointer member.The Copy Constructor The constructor that takes a single parameter that is a (usually const) reference to an object o
49、f the class type itself is called the copy constructor. Like the default constructor, the copy constructor can be implicitly invoked by the compiler. The copy constructor is used to: 1.Explicitly or implicitly initialize one object from another of the same type; 2.Copy an object to pass it as an arg
50、ument to a function; 3.Copy an object to return it from a function; 4.Initialize the elements in a sequential container; 5.Initialize elements in an array from a list of element initializers. Forms of Object Definition Recall that C+ supports two forms of initialization (Section 2.3.3, p. 48): direc
51、t and copy.Copy-initialization uses the = symbol, and direct-initialization places the initializer in parentheses. The copy and direct forms of initialization, when applied to objects of class type, are subtly different. Direct-initialization directly invokes the constructor matched by the arguments
52、. Copy-initialization always involves the copy constructor. Copy-initialization first uses the indicated constructor to create a temporary object (Section 7.3.2, p. 247). It then uses the copy constructor to copy that temporary into the one we are creating: string null_book = 9-999-99999-9; / copy-i
53、nitialization string dots(10, .); / direct-initialization string empty_copy = string(); / copy-initialization string empty_direct; / direct-initialization For objects of class type, copy-initialization can be used only when specifying a single argument or when we explicitly build a temporary object
54、to copy. When dots is created, the string constructor that takes a count and a character is called and directly initializes the members in dots. To create null_book, the compiler first creates a temporary by invoking the string constructor that takes a C-style character string parameter. The compile
55、r then uses the string copy constructor to initialize null_book as a copy of that temporary. The initialization of empty_copy and empty_direct both call the string default constructor. In the first case, the default constructor creates a temporary object, which is then used by the copy constructor t
56、o initialize empty_copy. In the second case, the default constructor is run directly on empty_direct. The copy form of initialization is primarily supported for compatibility with C usage. When it can do so, the compiler is permitted (but not obligated) to skip the copy constructor and create the ob
57、ject directly. Usually the difference between direct- or copy-initialization is at most a matter of low-level optimization. However, for types that do not support copying, or when using a constructor that is nonexplicit (Section 12.4.4, p. 462) the distinction can be essential: ifstream file1(filena
58、me); / ok: direct initialization ifstream file2 = filename; / error: copy constructor is private / This initialization is okay only if / the Sales_item(const string&) constructor is not explicit Sales_item item = string(9-999-99999-9); The initialization of file1 is fine. The ifstream class defines
59、a constructor that can be called with a C-style string. That constructor is used to initialize file1. The seemingly equivalent initialization of file2 uses copy-initialization. That definition is not okay. We cannot copy objects of the IO types (Section 8.1, p. 287), so we cannot use copy-initializa
60、tion on objects of these types. Whether the initialization of item is okay depends on which version of our Sales_item class we are using. Some versions define the constructor that takes a string as explicit. If the constructor is explicit, then the initialization fails. If the constructor is not exp
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年嵩山少林武术职业学院高职单招职业技能测试近5年常考版参考题库含答案解析
- 2025年山东电子职业技术学院高职单招高职单招英语2016-2024历年频考点试题含答案解析
- 2025年山东海事职业学院高职单招高职单招英语2016-2024历年频考点试题含答案解析
- HSE安全培训知识课件
- 2025年天津渤海职业技术学院高职单招(数学)历年真题考点含答案解析
- 2025年天津生物工程职业技术学院高职单招职业技能测试近5年常考版参考题库含答案解析
- 纸浆班本课程汇报
- 秋天再见课件小班
- DB3204-T 1072-2024 化工园区污染地块土壤风险管控和修复施工过程环境管理规范
- 老年口腔健康教育
- GB 4053.2-2009固定式钢梯及平台安全要求第2部分:钢斜梯
- GB 14934-2016食品安全国家标准消毒餐(饮)具
- 民本思想课件
- 健身气功八段锦教案
- 象棋-小学社团活动记录表
- 边坡坡度测量记录表
- 中职 AutoCAD 2018计算机辅助设计项目化教程课程标准
- 功能医学与健康管理
- HZS75型搅拌站安装施工方法
- DB13(J)∕T 8377-2020 建筑施工安全管理标准
- 吊装施工施工组织设计
评论
0/150
提交评论