C + + notes (c + + features only)

Source: Internet
Author: User
Tags class definition

C + + review Note One (declaration definition of a class applied and constructor destructor section)
Const in C is "a variable that cannot be changed", whereas in C + + The seed is "a constant of type description", constants must be initialized and cannot be changed
const int *p=15;const on the left of *, so *p is constant and cannot be changed
int * Const P=15;CONST on the right side of *, so p is constant, but *p is not, *p is int, *p value can be changed
A const type reference can only be used with a const type and cannot be referenced by a normal type, because a generic type reference may modify the value of a const type
correct: const int A=5;const int;&b=a;
wrong: const int A=5;int &c=a
A const type reference can refer to normal data, but cannot change the value of ordinary data by reference;
A const type reference differs from the referenced type when a temporary variable is generated when it is initialized, and a const reference is cast after casting
A reference to a normal type is not the same as the referenced type, and cannot be passed.
reference access is a direct access to a variable, and the pointer needs to save the variable address, so it is an indirect reference
A reference is an alias of a variable that itself does not allocate its own memory space alone, it is not a separate variable, and the pointer has its own memory space,
a reference can no longer reference another variable once it is initialized, and the pointer may (not a const pointer)


comparison of three kinds of methods of transmitting parameters
1. Value passing: Arguments are initialized, parameters are allocated space, and the contents of the arguments are copied to the parameters
2. Pointer passing: The essence is still the value pass
3. Reference pass: No space is allocated when the argument is initially taxiing


C + + is the reason of facing object thought, with three characteristics of encapsulation, inheritance and polymorphism.
Encapsulation is the foundation, inheritance is key, polymorphism is complementary


the general form of a class definition:
class< class name >
{
public: (Common)
protected: (Protected)
priovate: (private)
};


Definition of Object < class name >< object name >


the difference between a class and a struct
1. Default access rights, the struct's access rights are public (common), and the class is private (proprietary), without intentionally declaring access rights
2. Differences in initialization, classes can initialize data members through constructors and destructor classes, and structs can only be initialized with method-specific


initializes the data member in the constructor, and automatically calls the constructor to initialize the data member whenever the object is created
constructor has no return type and cannot be a virtual function
in the definition of Yes, if the data member of the class is an object of another class, when the constructor is called to create the object, the constructor for the object that is the data member is called automatically first


the sum of the destructor features:
1. No return type
2. No parameters
3 cannot be called arbitrarily (can be called)
4. Cannot be overloaded (constructors have parameters or can be overloaded)
5. The function of the destructor and constructor corresponds, so add a logical inverse operator "~" in front of the function


The following conditions require a destructor:
1. When an object ends its life cycle, such as an object defined in the function body, the local object is freed when the function call ends
2. Constructor to open a file, when you finish using the file, you need to close the file
3. The dynamic memory area is allocated from the heap and must be released before the object disappears


Constructors Call Others first, destructors call their own


the initialization of a const member can only be done in the constructor initialization list, the initialization of the reference member can only be done in the constructor initialization list, the object member that has the constructor (the class for which the object corresponds does not have a default constructor), or only in the constructor initialization list


the function of a conversion constructor is to convert a different type of data into an object of a class, which becomes a conversion constructor when a constructor has only one parameter and the parameter is not a const reference to this class .
when the constructor of a single argument is preceded by the explicit keyword, the conversion construct is blocked, and the object is also blocked when the definition object is initialized with an equals sign
Example:
class TT
{
Public :
TT (int data) {m_data=data;}
Private:
int m_data;
};
tt obj = 10;//cannot be converted from int to TT;


constructors can be overloaded, so C + + chooses the appropriate constructor based on the argument type and number of the class weight declaration constructor


C + + stipulates that each class must have a constructor that does not create any objects without constructors, and if a constructor for a class is not defined, C + + provides a default constructor, which is a parameterless constructor that is solely responsible for creating the object without doing any initialization work
as long as a class defines a constructor, C + + no longer provides a default constructor, and if you need a parameterless constructor, you need to define it yourself, similar to defining a variable, if you create a global object or a static object when you create the object with the default constructor, the object member data is all 0. When a local object is created, its member data is a meaningless random number
A class If nothing is called an empty class, the size of an empty class is one byte, and the compiler implicitly generates 6 members for it:
1. Default constructors
2. Default Copy construction
3. Default destructor
4. Default assignment operator overloading
5. Default address operator overloading
6. Accessor operator Const


C + + provides a way to create and initialize another object with one object value, and the copy constructor is done for that function
The format of the copy constructor is as follows
< class name >::< copy constructor name > (< class name >&< reference name >)
Tt::tt (tt&obj)
If a copy constructor is not defined in a class, the system automatically generates a default copy constructor that copies the values of all data members of a well-known object to the data members of the corresponding object
features of the copy constructor:
1. Copy constructors have the same name as the class, no return type
2. The copy constructor has only a single parameter, which is a reference to the class object
the copy constructor has two main uses in addition to creating a new object of its kind using the values of a well-known object:
1. When the object is called as a real parameter, the system automatically calls the copy constructor to pass the object value to the Parameter object.
2. When the return value of a function is an object, the system automatically calls the copy constructor to create a temporary object for the returned object value, and then assigns the temporary object to the object that accepts the function's return value

Summarize:
A constructor is a special member function that is used to create an object, calls it to allocate space for a class object, assigns an initial value to his data member, and other requests for resources, a destructor is a special member function used to revoke an object and reclaim its resources, which is complementary to the function of the constructor and appears in pairs.
Each class object must be born in a constructor, a class may define one or more constructors, and the compiler compares the parameters of the object constructor declaration with the real parameters of the created object to determine which constructor to use, with the normal overloaded function using the method type. When a class object containing an object member is created, the object member needs to be created, corresponding to the constructor that invokes the object member
The copy constructor is used to create a new object from a known object
Default constructors and default destructors are used in cases where constructors and destructors are not explicitly defined in a class to create an object (a value that allocates a data member's storage space, cannot initialize a value), and automatically invokes the default destructor to undo an object and reclaim resources


C + + review Note two (static member and friend function)
Global object is a way to realize data sharing, because it is visible everywhere, so it is not safe enough, should try to use less global objects in the program, implement data sharing between multiple objects of the class, can use static members

Static members include static data members and static member functions, and the friend function is also a common C + + function, but it can access the protection or private members of a class, facilitates programming, improves efficiency and destroys the encapsulation of classes.

In a class, if a data is described asStaticThe data is called static data, which tells the compiler that no matter how many objects in the class are created, there is only one copy of the static data, the copy is shared by all class objects, the static data belongs to the class, it is not unique to the object, its value is the same for each object, it is worth updating to the static data member, That is, the static data member for all objects is worth updating, the port has no background data using the keywordStatic, static data members are described in the class body, defined outside the class body, to allocate space and initialize.

Static data members can be applied in the following ways:
1. Number of objects used to hold flow changes
2. As a flag indicating whether a particular action occurred
3. Pointers to the first or last member of a list

Static member functions
Access to static member functions can be used in the following ways:
< class name >.< static member function name > (< parameter table >)
Classa::fun (123,456);
Or
< object name >.< static member function name > (< parameter table >)
Obja.fun (123,456)

Static member functions belong to only one class and do not belong to any object in the class
Static functions are described and defined in the same way as static data, where a function implementation can be in the class or outside the class body, the same as a general member function
In the implementation of a static member function, static members can be used directly, and non-static members can be used through class objects

Friend £ º
Classes are encapsulated, private data in a class is accessible only through member functions of the class, and if a private member of the class needs to be accessed in the program, the member functions of the class must be called through the object, and frequent invocation of member functions will affect the efficiency of the program's operation
In order to solve the above problems, C + + provides a friend wit, friend can not call the member function can directly access the private data of the class, in order to improve the efficiency of the program, the friend mechanism in the data encapsulation of the opaque wall opened a small hole, so that UF yuan to be cautious, friend can be a function, Called a friend function, a friend can also be a class, called a friend class

When life one Class A is a friend of another class B, all member functions in the friend Class A are friend functions of class B

Summary: Using static data members is better than using global variables, the problem with global variables for object-oriented programming is to violate the principle of data encapsulation, to use static member data must allocate space and initialization before the main () program runs, and static members are not associated with any particular object of the class. The role of friends is mainly to improve the program's operational efficiency and convenient programming, but with the improvement of hardware performance, the role of the fate is no longer obvious, on the contrary, friends have broken the packaging of the class, so use need to weigh the pros and cons.


C + + review note three (operator overloading)
In addition to the following four operators, other operators can be overloaded
1. Conditional operator?:
2. The component operator.
3. Scope resolution operators::
4. Take the size operator sizeof

Operator overloading to keep the following attributes of the original operator unchanged:
1. Priority and adhesion unchanged
2. The number of operations is the same
3. The grammatical structure does not change

Operator overloading is actually done by defining a function.
Operator overloading is ultimately the overloading of functions, and the compiler chooses overloaded operators to follow the selection principle of function overloading, that is, to select different overloaded operators according to different types or number of arguments
Operators should conform to the usage habits, easy to understand
If the "*" operator is overloaded with a merge operation of two objects in a string class, it is better to overload the "+" operator to make it easier to understand
Operator overloading does not create new operation symbols
For example, you cannot create a "* *" to calculate power
In C + +, operator overloading is implemented by operator overloading functions, and operator overloading functions generally take one of the following two forms:
1. Form of member functions
2. Form of a friend function

Operator overloading in the form of member functions
< function type >< class name >::operator< symbol > (parameter table) {operator overloaded function body}
int classa::opreator+ (int a,int B) {}

The parameter table lists the operands that the operator requires, no parameters in the single-operation parameter table, the object that calls the function is the operand, the binocular operation parameter table has a parameter, the object that invokes the function is the first operand, the parameter in the parameter table is the second operand, and the operator function body has a new explanation for the meaning of the overloaded operator. This explanation is confined to classes that overload the operator, and the operator means that the function body is interpreted; otherwise, the operator has the predefined meaning of the system.

Summarize:
Using operator overloading makes the program easier to understand and easy to manipulate, but it should be noted that operator overloading cannot alter the precedence and binding of the operator itself, cannot alter the number of operands, or invent new operators, if the copy constructor and assignment operator are not defined in the class, The compiler will provide default copy constructors and assignment operators, but only for simple class objects
The operator overload function can be defined as a member function and a friend function, the invocation of the operator overload function is displayed and implicit, in the pre-increment and post-increment budget acid service definition, the use of the shape parameter int, only for the logo and before and after different, no other role, The copy constructor creates a new object of the same class with an existing object, while the assignment operator assigns the member variable of an object to a member variable of the same name that already exists for the same object.

C + + review note four (derivation and inheritance)
Inheritance in C + + is divided into single inheritance and multiple inheritance
Single inheritance: Only one direct base class inherits from a derived class
Multiple inheritance: Derived classes have multiple inheritance methods for direct base classes

Defined format for derived classes
Class < Derived classes names >:< inheritance methods >< base class names >
{
Definition of a new member in a derived class
}
There are three ways of inheriting:
Public (common inheritance)
Each member in the base class maintains the same access rights in the derived class
Private (privately inherited)
Each member of a base class is a private member in a derived class and can no longer be inherited by a derived subclass
Protected (Protection Inheritance)
Both public and protected members in the base class are protected members in the derived class, and private members are still private in the derived class
Regardless of inheritance, member functions and friend functions in derived classes can access public and protected members in the base class, but cannot access private members
In the case of public inheritance, the object of a derived class can only access public members, and in the protection of inheritance and private integration, the object of the derived class cannot access any member of the base class

Multiple inheritance has more than one base class, the base class name is separated by commas, and each base class name should have a description of how the base class inherits
Class < Derived classes name >:< inheritance method >< base class name >,< inheritance method >< base class name 2>
{
Definition of a new member in a derived class
}
The default inheritance mode is private inheritance

You can declare a public member in a base class from a private-inherited derived class in a derived class using the < base class >::< member name > declaration method so that the child class object of the derived class can access the member

constructors/destructors in derived classes
Through inheritance, a derived class contains all of its base class members, and the data structure of the derived class object is composed of the data members described in the accumulation and the data members described in the derived class, and when the derived class object is created, the initialization of the derived class object is not only to comfort the data members in the derived class, It also initializes the data members in the base class, and if there are child objects in the derived class, it should also contain the child object class.
< derived class names > (< General Staff tables >):< base class constructor names > (parameter Table 1), (sub-object name) (parameter Table 2)
{
Initialization of data members in \ \ derived class
}
The constructor is called in the following order
1. Base class constructors
2. Derived class constructors
When you execute a destructor for a derived class, you also call the destructor for the base class and the child object
The order of the destructors is as follows
1. Call a destructor for a derived class first
2. destructor of the base class

Member redefinition of a class
A redefinition is a mechanism that a subclass needs to use to modify or extend a member function that accumulates.
Redefine the redefinition of a data member of a base class, or a redefinition of a base class member function, respectively
New redefined members can be exactly the same as the base class, or they can be different from the same name as the base class function

Attention:
1. Regardless of whether the parameters of the member function overloaded by the subclass are identical to the base class, the overloaded
2. redefinition refers to the same name of a member function defined in a different scope, with different parameters or the same condition
3. A redefined member overrides its parent class member

constructor format for multiple inheritance derived classes
< derived class name > (General Staff Tables):< base class name, (parameter table),< base class name 2>, (parameter Table 2),< sub-object name;, (parameter table)
{
Derived class constructors
}
TTC (int a): TTB (j), TTA (j), M_nnum (15)
{
Derived class constructors
}
Execution order: a constructor that limits all base classes, and then executes the constructor of the derived class itself, including child objects

The two semantic problems in multi-inheritance
In general, member access in derived classes is unique, but in the case of multiple inheritance, it is possible that derived classes are not unique to their class member access, that is, ambiguity, and here are two cases where there are two semantics:
1. Ambiguity may occur when calling a member of a different class with the same name
2. Ambiguity may occur when accessing members of a common base class
The solution is to use the class name to qualify the:< derived class object name; base class Name:: member name;

The virtual base class description format is as follows:
Class < base class name >
Class < Derived classes name: Virtual < inheritance >< base class name >
Class < Derived classes name >:virtual public Cclassa

The purpose of introducing the virtual base class is to solve the problem of two semantics by using respect to produce a base class sub-object in its derived class object
If a derived class has more than one direct base class, and these direct base classes have a common base class, then in the final derived class, the multiple copies of the same member with the same name as the indirect common base class data members are preserved, and the method of the virtual base class provided by C + + allows only one member to be retained when inheriting the indirect common base class

Summarize:
The C + + support class inherits wit, and inheritance is one of the important concepts of object-oriented, and the member functions and friend functions of derived classes can access all of the accumulated public and protected data members and member functions
Derived class objects can access only the public data members and member functions of the base class, and multiple inheritance is a mechanism by which a class derives from multiple base classes, and derived classes actually acquire the attributes of all base classes
When a class is a derived class of two or more base classes, the class name of all base classes must be listed after the derived class name and colon, and the base class is separated by commas, and the constructor of the derived class must activate the constructors of all base classes and pass the corresponding arguments to them
A derived class can be another base class. This is equivalent to the formation of an inheritance chain, when the constructor of a derived class is activated, all of his base class constructors are also activated, in order to solve the two semantic problem in multiple inheritance, introduced the concept of virtual base class, seven acres is to make the public base class in its derived object middle finger rest their lives a base class sub-object


C + + review Note five (polymorphism vs. virtual function)
A virtual function is a non-static member function that is defined in the following format:
Virtual < type specifier >< function name > (parameter table)
{
function body
}
virtual void fun_s ()
{
function body
}
Where virtual is the key word
If a member function in a class is described as a virtual function, the member function may be in a different implementation version of the derived class
Because of the existence of virtual functions, the compiler will make dynamic union, so that the object calling virtual function is determined at run time, in order to realize the polymorphism of dynamic Union
The conditions in which a base class function has a virtual attribute are:
1. In the base class, describe the function as a virtual function (virtual)
2. Defining a public derived class for a base class
3. Overloading the function in the public derived class of the base class
4. Define a pointer variable to the base class, which points to the object of the derived class of the base class

Overloaded virtual functions are not generic overloaded functions, which require a function name. return type, number of arguments, parameter type and order exactly
Because virtual functions are overloaded, virtual functions in derived classes can omit the virtual key for money

Overloading: Different implementations of the same function [scope same, function name is the same, parameter name is different]
Redefine: Subclasses override base classes with the same name function [scope different, function name is the same, parameters can be the same or different]
overriding: Subclasses overwrite functions with the same name as the base class, with the same type of function [different scope, same function name, same parameter]

Pure virtual function and abstract class
Pure virtual function is a kind of special virtual function, it is a virtual function without concrete implementation, and its definition format is as follows:
class< class name >
{
Virtual < functions type >< function name > (parameter table) = 0;
}
Class TT
{
virtual void XXXX () = 0;
}
In many cases, it is not possible to give a meaningful implementation of a virtual function in a base class, but to declare it as pure virtual function, and its implementation is left to the derived class of the base class, which is the function of pure virtual function.
virtual function Encounters interface template, cannot be instantiated directly, need derived class to implement function definition
reflect the characteristics of the design of the object to delete easily, easy to modify, easy to share
If a pure virtual function is defined in a class, the class becomes an abstract class, and C + + stipulates that the abstract Liu type will no longer be able to define the object

Virtual destructor
Constructors cannot be described as virtual functions, and destructors can be described as virtual functions by adding the keyword virtual specifier before the destructor, and if a destructor of a base class is described as a virtual function, the destructor in its derived class is also the virtual seat dog function, then the virtual specifier is omitted
Virtual destructor can be dynamic-linked, can choose the destructor at run time, can ensure that the destructor description is the correct execution of virtual destructor, therefore, in the case of inheritance, it is no harm to describe the destructor of the base class as virtual destructor.
It should be noted that the virtual destructor is generally used in the base class, the swimsuit prevents the derived class object delete base class pointer caused by the memory leak, the base class destructor is a virtual function, and derived from the cow has a custom destructor implementation, delete the base class pointer when a colleague calls the derived class destructor, If the base class destructor is not a virtual function, then the destructor of the base class is called long, and the destructor of the base class cannot release the other resources of the derived class

C + + notes (c + + features only)

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.