文档详情

Using Classes in C++ dalereed(在c++ dalereed使用类).pdf

发布:2017-08-29约5万字共20页下载文档
文本预览下载声明
Using Classes in C++ Note: Many of the examples given below are taken from the Irvine book I. Creating Classes A. An Example [from Deitel Deitel]: structs vs. classes Drawbacks to using a struct: 1. Initialization not specifically required, and may be done incorrectly 2. Invalid values can be assigned to struct members (as in example) 3. If struct implementation changes, all the programs using the struct must also change 4. Structs aren’t first-class : they cannot be printed as a unit or compared B. Class Definition Basic form is: class class-name { member-list }; Class name has file scope and external linkage. E.g. Point class for points on a 2D cartesian graph: class Point { public: int GetX(); // Returns the value of x. void SetX(); // Sets the value of x. private: int x; // x-coordinate int y; // y-coordinate }; Keywords public and private are access specifiers. Note that storage is not allocated until an instance of the class is created (there is also an access specifier protected , which we will avoid for now) C. Class Objects General format is: class-name identifier. We can access class methods using the dot operator (.), E.g. Point P; // Note this is different than Point P(); P.SetX( 300 ); cout x-coordinate is: P.GetX(); Copying from one class object to another by default does a bit-wise copy, such as Point P1, P2; ..
显示全部
相似文档