版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、裝訂線安徽工業(yè)大學 畢業(yè)設計(論文)說明書共 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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年環(huán)保技術與設備購銷合同
- 2024年版餐廳后廚管理合同2篇
- 《走上辯論臺》教案
- 2024年廣告創(chuàng)意設計與執(zhí)行合同模板3篇
- 小學生語文學習計劃
- 存量房買賣合同(15篇)
- 中國轉椅坐墊項目投資可行性研究報告
- 體育工作計劃范文合集五篇
- 員工安全生產承諾書
- 網絡大學生實習報告合集7篇
- 2024年度通信設備維修服務合同范本3篇
- 安恒可信數(shù)據空間建設方案 2024
- 2024年學校與家長共同促進家校合作發(fā)展協(xié)議3篇
- C預應力錨索框架梁施工方案(完整版)
- 參加團干部培訓心得體會
- 中華民族共同體概論專家講座第一講中華民族共同體基礎理論
- 湖北省襄陽市2023-2024學年高一上學期期末考試化學試題(含答案)
- 浙江省金華市十校2023-2024學年高一上學期1月期末考試物理試題 含解析
- 物業(yè)管理師考試題庫單選題100道及答案解析
- 校園智能安防系統(tǒng)安裝合同
- 2024年專利代理人專利法律知識考試試卷及參考答案
評論
0/150
提交評論