C ++ Class & amp; object,

Source: Internet
Author: User

C ++ Class & object,

Note: Most of the content in this article comes from the networkHttp://www.runoob.com/cplusplus/cpp-classes-objects.html)Here, record your learning process.

I. Introduction

1. The class is used to specify the object format. It contains the data representation method and the method used to process the data. The data and methods in the class are called the members of the class. A function is called a member of a class.

2. The class provides a blueprint for the object, so basically, the object is created based on the class. Declare an object of the class, just like declaring a variable of the basic type.

Ii. class member functions

1. member functions of a class refer to the functions that write definitions and prototypes inside the class definition, just like other variables in the class definition. A class member function is a member of a class. It can operate any object of the class and access all members of the object.

2. member functions can be defined within the class definition or used independently.Range parsing OPERATOR ::. The member function defined in the class definition declares the functionInlineEven if the inline identifier is not used.

1 class Box 2 {3 public: 4 double length; // length 5 double breadth; // width 6 double height; // height 7 8 double getVolume (void) 9 {10 return length * breadth * height; 11} 12 };

Or

1 double Box::getVolume(void)2 {3     return length * breadth * height;4 }

Iii. Constructor

1.ConstructorIs a special member function of the class.Execute each time you create a new object of the class.

2. the constructor name and class name are identical, and no type or void is returned. Constructors can be used to set initial values for some member variables.

Iv. destructor

1.DestructorIs a special member function of a class. It is executed every time a created object is deleted.

2. The name of the Destructor is exactly the same as that of the class, but a Tilde (~) is added to the front (~) As a prefix, it does not return any value, nor can it contain any parameters. The Destructor helps to release resources before jumping out of a program (such as shutting down files and releasing memory.

Note:Delete A Class ObjectThe Destructor is called;Program out of object scopeThe Destructor is called.

5. copy constructors

Copy constructorIs a special constructor. When creating an object, it uses an object created before the same class to initialize the newly created object. The copy constructor is usually used:

  • You can use another object of the same type to initialize the newly created object.

    1 Box box2=box1;

     

  • The Copied object passes it as a parameter to the function.

    1 printwidth(box1);

     

  • Copy the object and return the object from the function.

If no copy constructor is defined in the class, the compiler will define one. If the class has pointer variables and dynamic memory allocation, it must have a copy constructor. The most common form of a copy constructor is as follows:

1 classname (const classname & obj ){//ObjIs an object reference, which is used to initialize another object. 2 // subject of the constructor 3}

Vi. User Functions

The friend functions of a class are defined outside the class, but have the right to all private members and protected members of the class. Although the prototype of the friend functions has appeared in the class definition, the friend functions are not member functions.

Youyuan can be a function called youyuan function. youyuan can also be a class called youyuan class. In this case, the entire class and all its members are youyuan.

If you want to declare a function as a friend of a class, you need to use the keyword before the function prototype in the class definition.Friend, As shown below:

1 class Box2 {3    double width;4 public:5    double length;6    friend void printWidth( Box box );7    void setWidth( double wid );8 };

All member functions of the declared class ClassTwo are used as the friends of the class ClassOne. the following declaration must be placed in the definition of the class ClassOne:

1 friend class ClassTwo;

VII. inline functions

1. C ++Inline functionsIs usually used with the class. If a function is inline, the compiler places a copy of the code of the function in each place that calls the function during compilation.

2. Any modification to the inline function requires that all the clients of the function be re-compiled, because the compiler needs to re-replace all the code once, otherwise the old function will continue to be used.

3. If you want to define a function as an inline function, you need to place a keyword before the function name.InlineBefore calling a function, define the function. If more than one defined function is defined, the compiler ignores the inline qualifier.

4. All functions defined in the class definition are inline functions, even if they are not usedInlineDescription.

Tip:

Define a function as an inline function only when there are 10 or even fewer rows.

Definition: After a function is declared as an inline function, the compiler expands the function inline instead of calling it according to the common function call mechanism.

Advantage: When the function body is small, inline functions can make the target code more efficient. inline functions are encouraged for access functions and other function bodies that are short and have critical performance.

Disadvantage: Misuse of inline will lead to program slowdown. inline may increase or decrease the amount of target code, depending on the size of the inline function. inline very short access functions usually reduce the code size, but inline a very large function will dramatically increase the code size. because modern processors make better use of instruction caching, compact code is often executed faster.

Conclusion: a more reasonable empirical rule is to avoid inline functions with more than 10 rows. exercise caution when dealing with destructor, which often looks longer than its surface, because there are implicit members and base class destructor called!

Another practical empirical principle: inline functions that contain loops or switch statements are often outweighs (unless in most cases these loops or switch statements are never executed ).

Some functions are not necessarily inline by the compiler even if they are declared as inline. This is important. For example, virtual functions and recursive functions are not normally inline. generally, recursive functions should not be declared as inline functions. (recursive call stack expansion is not as simple as a loop. For example, the number of recursive layers may be unknown during compilation. Most compilers do not support inline recursive functions ). the main reason for virtual function inline is to put its function body in the class definition, for the convenience of the graph, or as a document to describe its behavior, such as short access functions.

 8. this pointer

In C ++, every object can passThisPointer to access your own address.ThisPointer is an implicit parameter of all member functions. Therefore, within a member function, it can be used to point to the called object.

None of the membership functionsThisPointer, because youyuan is not a member of the class. Only member functions are available.ThisPointer.

The following examples help you better understand the concept of this pointer:

1 # include <iostream> 2 3 using namespace std; 4 5 class Box 6 {7 public: 8 // constructor Definition 9 Box (double l = 2.0, double B = 2.0, double h = 2.0) 10 {11 cout <"Constructor called. "<endl; 12 length = l; 13 breadth = B; 14 height = h; 15} 16 double Volume () 17 {18 return length * breadth * height; 19} 20 int compare (Box box) 21 {22 return this-> Volume ()> Box. volume (); 23} 24 private: 25 double length; // Length of a box26 double breadth; // Breadth of a box27 double height; // Height of a box28 }; 29 30 int main (void) 31 {32 Box Box1 (3.3, 1.2, 1.5); // Declare box1_box Box2 (8.5, 6.0, 2.0 ); // Declare box234 35 if (Box1.compare (Box2) 36 {37 cout <"Box2 is smaller than Box1" <endl; 38} 39 else40 {41 cout <"Box2 is equal to or larger than Box1" <endl; 42} 43 return 0; 44}

 

Compilation execution result

1 Constructor called.2 Constructor called.3 Box2 is equal to or larger than Box1

 

9. pointer to class

A pointer pointing to a C ++ class is similar to a pointer pointing to a structure. to access a member pointing to a class pointer, you must use the member access operator>, just like accessing a pointer pointing to a structure. Like all pointers, you must initialize the pointer before using the pointer.

10. Static members of the class

1. UseStaticYou can define a class member as a static keyword. When the declared class members are static, this means that no matter how many class objects are created, the static members have only one copy.

2. Static members are shared among all objects of the class. If no other initialization statement exists, all static data is initialized to zero when the first object is created.

3. static member initialization cannot be placed in the definition of the class, but the range parsing operator can be used outside the class.::To redeclare static variables and initialize them.

If you declare a function member as static, you can separate the function from any specific object of the class. Static member functions can be called even if the class object does not exist,Static FunctionsYou only need to use the class name plus range resolution Operator::You can access it.

Static member functions can only accessStatic Member Data,Other static member functionsAndOther functions outside the class.

Static member functions have a class range, theyIt cannot be the this pointer of the category class.. You can use static member functions to determine whether some objects of the class have been created.

Differences between static member functions and common member functions:

  • Without the this pointer, a static member function can only access static members (including static member variables and static member functions ).
  • A common member function has the this pointer, which can be any member of the member class. A static member function does not have the this pointer.
1 # include <iostream> 2 3 using namespace std; 4 5 class Box 6 {7 public: 8 static int objectCount; 9 // constructor defines 10 boxes (double l = 2.0, double B = 2.0, double h = 2.0) 11 {12 cout <"Constructor called. "<endl; 13 length = l; 14 breadth = B; 15 height = h; 16 // 117 objectCount ++; 18} 19 double Volume () is added each time an object is created () 20 {21 return length * breadth * height; 22} 23 static int getCount () 24 {25 return objectCount; 26} 27 private: 28 double length; // length 29 double breadth; // width 30 double height; // height 31}; 32 33 // initialize static member 34 int Box: objectCount = 0; 35 36 int main (void) 37 {38 39 // The total number of output objects before the object is created 40 cout <"inpartition Stage Count:" <Box: getCount () <endl; 41 42 Box Box1 (3.3, 1.2, 1.5); // declare box143 Box Box2 (8.5, 6.0, 2.0 ); // declare box244 45 // total number of output objects after the object is created 46 cout <"Final Stage Count:" <Box: getCount () <endl; 47 48 return 0; 49}

 

Compilation execution result

1 Inital Stage Count: 02 Constructor called.3 Constructor called.4 Final Stage Count: 2

 

11. Comprehensive Test Experiment

Run the test code and the output result is as follows:

1 # include <iostream> 2 3 using namespace std; 4 5 class Box {6 double width; // The default access modifier is private 7 double * high; // [when the class member variable is a pointer, you need to apply for memory for it in the constructor and copy constructor, and delete the memory in the Destructor] 8 public: 9 void setWidth (double wid); 10 void setHigh (double hig); 11 double getHigh (void); 12 Box (double wid, double hig); // constructor 13 ~ Box (void); // destructor 14 Box (const Box & obj); // copy the constructor 15 16 friend void printwidth (Box box ); // youyuan function 17}; 18 void Box: setWidth (double wid) 19 {20 width = wid; 21} 22 void Box: setHigh (double hig) 23 {24 * high = hig; 25} 26 double Box: getHigh (void) 27 {28 return * high; 29} 30 Box: Box (double wid, double hig) 31 {32 cout <"Call constructor" <endl; 33 width = wid; 34 high = new double; // request memory 35 * high = hig; 36} 37 Box ::~ Box (void) 38 {39 cout <"Call destructor and release memory" <endl; 40 delete high; // release memory 41} 42 Box :: box (const Box & obj) 43 {44 cout <"Call copy constructor" <endl; 45 width = obj. width; 46 high = new double; // memory application 47 * high = * obj. high; 48} 49 // The youyuan function is not a class member variable, but must declare 50 void printwidth (Box box Box) in the class) 51 {52 cout <"call friend functions" <endl; 53 cout <"width of box:" <box. width <endl; 54} 55 void printhweigh (Box obj) 56 {57 cout <"high of box:" <obj. getHigh () <endl; 58} 59 // main function 60 int main () 61 {62 Box box1 (12, 15); 63 Box box2 = box1; 64 65 // output width, high66 printwidth (box1); 67 printhigh (box1); 68 printwidth (box2); 69 printhigh (box2 ); 70 71 // Set width, high72 box2.setWidth (13); 73 box2.setHigh (16); 74 75 // output width, high76 printwidth (box1); 77 printhweigh (box1 ); 78 printwidth (box2); 79 printhigh (box2); 80 81 return 0; // call the Destructor (release box1, box2) 82}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.