C + + Classes and objects (05)

Source: Internet
Author: User
Tags function prototype

A class is an entity with a unique identifier, and any member declared in a class cannot be decorated with the extern, auto, and register keywords, a variable declared in a class belongs to that class, and in some cases a variable can be shared by different instances of that class.

Access permissions are used to control the accessibility of a member of an object in a program, and if no keyword is used, all members are declared as private permissions by default.

Defining member functions

The member functions declared in a class are used to manipulate data members, and they must also be implemented in a program. The general form of defining member functions is as follows:

return type class Name:: member function name (argument list) {function Body of member function//internal implementation}

where "::" is the scope operator, "class name" is the name of the class to which the member function belongs, "::" the member function that follows the table name belongs to this particular class.  In other words, the "class name:: member function name" means defining a member function that belongs to the class name, and the return type is the type of the return value of the member function.  You can also use the keyword inline to define a member function as an inline function. if the definition of a member function is given in the class at the same time that the class is declared, the default is an inline function.

assigning values to data members

You cannot assign a value to a data member inside a class. is not allowed outside of the class body. The specific value of the data member is used to describe the properties of the object. These data values are meaningful only if a specific object is produced. If the object's data member has a specified value when the object is produced, it is called the initialization of the object .

Objects that use classes

Both objects and references use the operator "." Access the members of the object, and the pointer uses the "->" operator.

(1) A member function of a class can directly use the private members of its own class (data members and member functions)

(2) functions outside the class cannot directly access the private members of the class (data members and member functions)

(3) functions outside the class can only use the public member functions of the class through the object of the class.

Creates an object by allocating memory to the object while the program is running. When creating an object, the class is used as a template, so the object is called an instance of the class.

The syntax for defining a class object pointer is as follows:

Class Name * object pointer name;

Object pointer name = Address of object;

Initialization can also be done directly.

Class Name * Object pointer name = Address of object;

A pointer to a class object can access the members of an object by using the "--" operator, that is: Object pointer name, object member name

Data Encapsulation

Object-oriented programming is the creation of a block-based memory area for data and code that provides a programmatic way to modularize a program, which can be used as a template to create a copy of it when needed.  According to this definition, an object is an area in the computer's memory that, by blocking the memory, each module (that is, the object) remains functionally relatively independent. Objects are considered entities that can act, and objects use these actions to accomplish each other's functions. In other words, an object is like a smaller computer with specific functionality that has data and code on the host computer and can communicate with each other.

operator NEW

The operator new is used to establish a controllable lifetime object, and new returns a pointer to the object. Because the class name is treated as a type name, the syntax for creating dynamic objects using new is similar to the syntax for building dynamic variables, and the difference is that new and constructors are used together. Dynamic objects created with new can only be deleted with delete in order to free up the occupied space. You should develop the habit of releasing unused memory space in a timely manner.

Assignment constructors

The compiler establishes a default copy constructor, and the default copy constructor uses the existing object as a copy to create a new object, so it is literally a copy constructor. Programmers can define their own copy constructors, and for Class A the copy constructor is prototyped as follows:

A::a (a&)  

From this function prototype, first it is a constructor, because after all, it is creating a new object. Second, his arguments are special, referencing the class's own object, which is to create a new object with an existing object. The use of references is considered in terms of the execution efficiency of the program. In order not to change the original object, the more common form is to use the const qualification as follows: A::a (const A &)

Destructors

When an object disappears, the memory allocated by the constructor should be freed using a destructor. constructors, assignment constructors, and destructors are the basic members of a stereotype member function, and they should be thoroughly understood and mastered in their design methods.

The call destructor is also done by the compiler, so the compiler must always know which function should be called. The easiest and most logical way to do this is to specify that the function has the same name as the class name. To differentiate from a destructor, precede the destructor with a "~" sign (still called the destructor with the same name as the Class). When you define a destructor, you cannot specify any return type , even if you specify the type of void type return. destructors also cannot specify parameters, but can be shown to indicate that the parameter is void, that is, a shape such as a::~a (void). From the perspective of function overloading, a class can define only one destructor and cannot specify parameters so that the compiled system is automatically called.

Destructors are called automatically at the end of an object 's lifetime. When the lifetime of the object ends, the program calls the destructor for the object, and then reclaims the memory occupied by the object.  Destructors for global objects and static objects are called before the end of the program runs. The destructor is called once for each element of the object array of the class. A destructor for a global object array is called before the program ends.

destructor and operator delete

The operator delete works with the destructor. When using the operator delete to delete a dynamic object, he first calls the destructor for the dynamic object and then releases the memory occupied by the dynamic object, which is the reverse of the process of creating a dynamic object using new.

When you use Delete to release a dynamic object array, you must tell the dynamic object array that there are several element objects, and C + + uses "[]" to implement. i.e. Statement delete[] ptr

When the program creates several objects successively, the system reconstructs the object according to the principle of post-build-first destruction. When a destructor is called with delete, it is refactored in the order of delete.

Default destructor

If a destructor is not defined when the class is defined, the C + + compiler also produces a default destructor that is empty for the function body.

This pointer

Using the this pointer ensures that each object can have its own data member, but the code that processes those data members can be shared by all objects.

C + + stipulates that when a member function is called , the system automatically passes an implied argument to it, which is a pointer to the object that called the function , thereby Causes the member function to know which object to manipulate . In a program, you can use the keyword this to refer to the pointer. The this pointer is a mechanism for C + + implementation encapsulation, which connects objects with the member functions called by the object, and externally, each object has its own member function.

Unless there is a special need, the symbol "This" is omitted in general and the system is set to default.

The nature of the object

(1) The objects of the same class can be assigned to each other.

(2) An array of objects can be used.

(3) You can use a pointer to an object , use the Fetch address operator & Place the address of an object in the pointer . Note that a pointer to an object cannot take the address of a data member, nor can it go to the address of a member function .

(4) An object can be used as a function parameter. object is used as a function parameter, you can use objects, object references, and object pointers.

(5) An object can be a member of another class.

Nature of the class

Permission to use classes

The data member is private, the member function is public:

(1) The member function of the class itself can use all members of the class (private and public members).

(2) The object of a class can only access public member functions.

(3) Other functions cannot use private members of the class, nor can they use public member functions, which can only use the class's public member function through the class's object.

(4) Although an object can contain another class, the class can only use the member function of that class through the object of the containing class, using the member function to use the data member.

File specification for object-oriented programming

It is generally required to place the declaration of a class in a header file, and a very simple member function can be defined in the declaration (the default inline function form), and the implementation is placed in the. cpp file. In the. cpp file, include the header file. The main program uses a single file, which is the multi-file programming specification.

C + + 's source program can contain various compilation directives to instruct the compiler to preprocess the source code before it is compiled. All of the compilation directives start with #, each with a single row, with no other compilation directives and C + + statements (note exceptions) on the same line. Compilation directives are not part of C + +, but extend the scope of use of the C + + programming environment to improve the organization and management of programs.

EMBED directive:

#include instructs the compiler to embed a source file in the source file with the # include directive where the directive is located. File names in angle brackets or double quotes can contain path information. For example: #include <\user\prog.h> Note: Because the compilation directives are not part of C + +, a backslash is used only when the backslash is represented here.

Macro definition:

The #define directive defines an identifier string that the compiler replaces with a defined string each time the identifier is encountered in the source program. The identifier is called a macro name, and the replacement process is called a macro substitution. #define指令用以进行宏定义, its general form is as follows: #define The macro name replaces the body, "macro name" must be a valid C + + identifier, "replace body" can be a sequence of characters consisting of any character. There is at least one space between the macro name and the replacement body. Note that the macro definition ends with a new line, not a semicolon . If a semicolon is given, it is also considered as part of the replacement body. When the replacement body is to be written on more than one line, a backslash is added to the end of each line in addition to the last line, indicating that the macro definition continues to the next line. Because the macro definition has many unsafe factors, you should use const instead of the macro definition when you need to use a parameterless macro. A macro name that is defined in one place of the program, and can be deleted with #undef when it is no longer used if you do not want it to affect other parts of the program

Conditional Compilation directives:

Conditional compilation directives are #if, #else, #elif和 #endif, which form an if-selection structure similar to C + +, where #endif represents the end of an instruction. The compile directive # if is used to control the compiler selectively compiling a portion of the source program. This section starts with # if and ends at #endif.  If the constant expression after # if is true, the part is compiled, or the part is not compiled, and this part of the code is equivalent to being deleted from the source file. The compile instruction #else establishes another option if the # if test fails. You can use compile directives in the #else branch to #error output error messages. #error使用的形式如下: #error error message "error message" is a sequence of characters.  When the #error instruction is encountered, the compiler displays an "error message" after it and aborts the compilation of the program. The compiler directives can be nested, and the nested rules and compilers will handle them in a similar way to the if expected nesting of C + +.

Define operator

The keyword defined is not an instruction, but a preprocessing operator that determines whether an identifier has been defined by a # define.  If the identifier identifier is defined by a # define, then defined (identifier) is true, otherwise false. Conditional compilation Directives #ifdef and #ifndef are used to test whether subsequent identifiers are defined by # define, and if they have already been defined, the #ifdef test is true, #ifndef测试为假; Ifdef test is False, #ifndef测试为真.

Using conditional compilation in a header file

C + + classes and objects (in)

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.