In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you what are the basic knowledge points of C++. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
I. the difference between new and malloc
1. New and delete are paired, and delete [] is required to release the array. New and delete actually call malloc and free, as well as the constructor and destructor of the class.
2. Malloc is paired with free. Malloc returns a void pointer, which needs to be strongly changed.
3. The memory applied by new is stored in the heap, and the memory applied by malloc is saved in the free storage area.
II. C++ operator
1. Mold operator:%
2. Logic No, and, or:!, & &, | |
3. Ternary operator:
C = (a > b)? A: b
4. Bitwise and, OR, non
& AND Logic and Logic AND
| | OR logic or Logic OR |
~ NOT complement to 1 (bit inversion) Complement to one (bit inversion)
5. By displacement:
> move SHR to the right Shift Right
Third, &: take the address operator and define variable references
The use of the & operator to get an address is: int* x address;.
However, another use is to define a variable alias, which is not simply the same as taking an address. It is easy to understand when passing function input parameters, but it is easy to cause misunderstandings when defining variables, especially the difference from pointers:
From a memory point of view, pointers and references are completely different. Pointer, memory to allocate a storage space for it. Reference, memory does not allocate space, reference is just an alias. I think it's just adding a flag to the symbol table, and for the statement int & yroomx; (& xroomy) it's true.
In fact, "reference" can do anything "pointer" can do, so why "reference" this thing? The answer is "do the right job with the right tools". When overloading an operator, you should use references. The most common example is the operator []. The typical use of this operator is to return a target object that can be assigned. If the operator [] returns a pointer, the latter statement is written as follows:
* v [5] = 10
But this makes v look like a vector pointer. So you will choose to have the operator return a reference.
Some of the rules referenced are as follows:
(1) when a reference is created, it must be initialized (the pointer can be initialized at any time), otherwise a compilation error will be reported.
(2) once the reference is initialized, the relationship of the reference cannot be changed (the pointer can change the object at any time).
In the following example program, k is initialized as a reference to I. The statement k = j does not change k to a reference to j, just changes the value of k to 6. Because k is a reference to I, the value of I also becomes 6.
The values of int I = 5; int j = 6; int & k = I; k = j; / k and I become 6
(3) there cannot be a NULL reference, which must be associated with a legitimate storage unit (the pointer can be NULL).
It is wrong to write below to point the address to a location of memory. The result will be uncertain (the compiler can produce some output so that anything can happen)
Char * pc = 0; / / set the pointer to null char& rc = * pc; / / make the reference point to null
(4) the "sizeof reference" gets the size of the variable (object) it points to, but when the reference is a member, it occupies the same space as the pointer (no standard is found).
(5) A reference can only point to an actual variable, not a pointer or reference.
(int*) * p1; / / p1 is the pointer of the pointer
(int*) & p2; / / p2 is a reference to an integer pointer
References cannot point to pointers or references!
(int&) * p3; / / ERROR: cannot have a pointer to a reference because the reference is just an alias
(int&) & p4; / / ERROR: cannot have a reference to a reference because the reference is just an alias
(6) there is not much difference between the internal implementation of pointers and references. But there are some things to pay attention to when using it. This is important because references have object behavior. The copy function of the object is called when referencing replication, which is prone to error when polymorphisms are involved.
Class A {...}; class B:public A {...}; void f (Atropa1Magaza2) {a1rooma2ramp / only the replication function of base class An is called here, and part B will not be copied, which will lead to data inconsistency (that is, the data of part B has not been copied); a1.fun ();}
IV. About const
General const variables:
The following two declarations both point to a pointer of type const int. The pointer to memory cannot be modified, but the pointer can point to another memory:
Const int * p
Int const * Q
The const pointer of type int should be declared like this. The memory that the pointer points to can be modified, but the pointer cannot point to another memory
Int * const r = & n
Declare a const pointer to the const int type:
Const int * const pairing n
The meaning of const in the function declaration:
Const int& SetPoint (const int& param) const
First const:
The return value of the function is limited to const, that is, the return value cannot be modified. Const int a=SetPoint (...) A cannot be modified after that.
Second const:
The formal parameter of a function is of type const, and the body of the function cannot be modified.
The third const:
Indicates that this function does not make any changes to the data members (non-static data members, to be exact) of this class object.
Initialization of const and static member variables of the class:
For static member variables, if they are also const, they can be initialized in the class definition, otherwise they can only be initialized outside the class definition.
Non-static const member variables can only be initialized in the initialization list of the constructor. (ClassName (): Macro1 (1) {};)
Syntax for some data types and variable assignment
1. All declared elements in union occupy the same amount of memory space, and their size is the size of the longest element in the declaration. One of the uses of union is to combine a longer primitive type with a structure (structure) or array (array) consisting of other smaller data types.
2. The assignment method of long double and float variables:
3.14159L / / long double
6.02e23f / / float
3. A definition statement that can easily lead to misunderstanding: int* ppene Q
At first glance, it seems that both p and Q are of type int*, but in fact, only p is a pointer, and Q is the simplest int variable. The syntax for defining two pointers simultaneously is: int * p1, * p2
4. Define a pointer variable to the int [4] array
Int (* p) [4] = RollNum
Here, p is declared as a pointer to a 4-element (int) array.
5. When no size is specified, the size of the char array is determined by the initialization string:
We can initialize the string mystring in either of two ways:
Char mystring [] = {'Haugh,' eBay, 'lump,' lump, 'ovoid,' / 0'}
Char mystring [] = "Hello"
In both cases, a string or array mystring is defined as six characters long (the element type is character char): the five characters that make up the Hello plus the last empty character ('/ 0'). In the second case, with double quotation marks, the empty character ('/ 0') is automatically added. In both cases, sizeof should be 6.
VI. Several commonly used standard C++ functions
1. The usage of cout and cin:
Cout "yyy"
2. Commonly used string functions:
Strcat / / string concatenation
Strcpy
Strncpy
Strcmp / / string comparison, the same returns 0
7. How to write switch-case
Switch (expression) {case constant1: block of instructions 1 break; case constant2: block of instructions 2 break;. . . Default: default block of instructions}
VIII. Several attributes and usages of functions
1. Specify the default parameter value of the function
Int divide (int a, int baggage 2) {
2. What is function overloading (Overloaded functions)
Two different functions can use the same name, as long as their parameters (arguments) have different prototype, which means you can give the same name to multiple functions if they use different numbers of arguments, or different types of parameters.
3. Inline function
The inline instruction can be placed before the function declaration, requiring that the function must be compiled in code form where it is called. This is equivalent to a macro. Its benefits are only valid for short functions, in which case the compiled code runs faster because it avoids the time it takes to call some routine operations of the function (overhead), such as parameter stack operations.
You don't need to write the keyword inline when calling a function, only before the function is declared.
4. Pass the array as an argument to the function, passing a reference instead of a value.
Void procedure (int myarray [] [3] [4])
IX. The use of function pointers
Several ways to use function pointers:
(1) simply call function pointer
Void (* pfunc) (int); pfunc=callback_funcname; callback_funcname (1)
The code that declares the function pointer prototype can be written either at the call or globally. This method is easy to use and is suitable for temporary calls.
(2) use typedef to call the function pointer:
Typedef void (* PFUNC) (int); PFUNC pfunc; pfunc=callback_funcname; callback_funcname (1)
This method is suitable for multiple calls, first defining the PFUNC globally, then declaring a temporary variable at each call place and then calling it.
(3) call member function pointers in C++ class (do not use typedef):
Void (* MyClass::pfunc) (int); pfunc=&MyClass::callback_funcname; (this- > * callback_funcname) (1)
Similar to method 1, note the difference in syntax.
(4) call member function pointer in C++ class (using typedef):
Typedef void (* PFUNC) (int); / / typedef PUNC pfunc; pfunc=&MyClass::callback_funcname; in the class (this- > * callback_funcname) (1)
Similar to method 2, pay attention to the differences in syntax.
10. The unusual usage of typedef
The general usage of typedef is:
Typedef int UINT32
But when used to define an array type or pointer function, it is special:
Typedef char CARRAY [32]; / / defines a type of CARRAY that represents char [32]
Typedef void (* PFUN) (int); / / defines a variable type that points to the pointer function. The function prototype is void xxx (int yyy).
11. The private/protected/public attribute of the class
1. If a member of the class does not specify an access domain, it defaults to private.
2. The identifier protected is similar to private, and the only difference between them is shown when inheriting. When defining a subclass, the protected member of the base class can be used by other members of the subclass, while the private member cannot.
3. The difference of public/protected/private inheritance:
(1) public inheritance: the public of the parent class is still public,protected and protected,private is still inaccessible
(2) protected inheritance: the public of the parent class is called protected,protected and is called private.
(3) private inheritance: all members of the parent class become private.
XII. About empty classes
What default functions does the compiler provide for an empty class?
1. The C++ compiler provides default constructors, destructors, copy constructors, and copy assignment operators (see article 5 of the famous third edition of Effective C++).
When we define a class without explicitly defining the constructor, the compiler automatically assumes two overloaded constructors (the default constructor "default constructor" and the copy constructor "copy constructor"). The copy constructor is a constructor with only one parameter (prototype: ClassName (ClassName & cn) {};), which is an object of the class. The function of this function is to copy the values of all non-static (non-static) member variables of the passed object (object) to its own object.
It is important to note that these two default constructors (empty construction and copy constructor) exist only if no other constructor is explicitly defined.
A class contains a default definition of the assignment operator assignation operator (=), which is used between two objects of the same kind. This operator copies all non-static (non-static) data members of its parameter object (the object to the right of the symbol) to the object to its left.
2. Declare an object in the way of class obj;. If the constructor has no arguments or only a default constructor, you cannot add () after it, because the compiler will mistakenly think that this is a function declaration with no arguments.
3. If any other constructor with arbitrary parameters is defined, neither the default constructor nor the copy constructor exists. In this case, if you want to have empty construction and copy constructor, you have to define them yourself.
4, for the basic type, in C++, for the template template, it is stipulated that they can use the default constructor similar to the class (only in a similar way) to assign an initial value of 0. This is called display initialization of basic types. Please refer to page 14 of the C++ standard library (The C++ Standard Library). 2.2.2 display initialization of basic types. The examples given in the book are
Int i1 / uninitialized
Int i2 = int (); / / initialized to 0
How much is an empty class equal to sizeof?
Sizeof an empty class returns 1. The so-called class instantiation is to assign an address in memory, and each instance has a unique address in memory. The empty class is also instantiated, so the compiler implicitly adds a byte to the empty class so that the empty class has a unique address after instantiation. So the sizeof of the empty class is 1. The C++ compiler does not allow objects to be zero length. Imagine how an object of length 0 is stored in memory? How do I get its address? To avoid this, C++ forces the class to insert a default member of a length of 1. If there is a custom variable, the variable replaces the default member.
XIII. The calling sequence of constructors in the case of inheritance or multiple inheritance
(1) if it is declared as Derive: public Super1, public Super2 {AnotherClass masked obj;}; the calling order of the constructor is: Super1, Super2, AnotherClass, Derive.
(2) if the parent class has a default constructor or a constructor with no parameters, it is not necessary to explicitly call the parent constructor in the constructor definition of the subclass, otherwise it needs to be called. The same is true of members. Using the above example, the constructor of Derive is written as follows:
Derive (int I): Super1 (I), Super2 (I), m_obj (1) {...}
Note that member objects should be initialized with the object name, not the class name.
The order in which destructors are called should be reversed in turn.
14. Virtual functions, pure virtual functions and abstract classes, virtual destructors
The function and operation principle of virtual function
(1) Polymorphism is a core concept in object-oriented programming, which means that a pointer to a base class type may actually point to a subclass object. Only at run time can you decide which function to execute according to the actual situation, that is, dynamic binding. Static binding corresponds to dynamic binding, which means that which function is called is determined at compile time. To achieve dynamic binding, the function of the parent class must be declared as virtual. If it is not declared as virtual, the result may not be expected.
For destructors, virtual functions ensure that both subclass and parent destructors are executed.
(2) for a class that contains at least one virtual function (or its parent class contains a virtual function), the compiler needs to add 4 bytes to the class to hold the pointer to the virtual function table VTABLE.
Pure virtual functions and abstract classes
Classes that contain pure virtual functions cannot be directly instantiated and can be called abstract classes. Definition method:
Virtual void func () = 0
The subclass override is a virtual function, and the virtual keyword is not necessary.
When do you need to specify a destructor as virtual?
(1) the destructor does not necessarily need to be defined as a virtual function, it needs to be defined as a virtual function only if this class is to be used as the parent of other classes. If the destructor of the parent class is not defined as a virtual function, the parent destructor will not be called when the subclass object is destroyed.
(2) for an abstract class, the destructor can be defined as pure virtual.
(3) the dynamic binding of virtual functions between parent and subclasses will not be affected by private.
(4) when the virtual functions of a class are called in its own constructor and destructor, they become ordinary functions, not "virtual". In other words, you can't make yourself "polymorphic" in constructors and destructors.
(5) the definition of virtual function and pure virtual function can not have static identifier, the reason is very simple, the function modified by static requires pre-bind at compile time, but the virtual function is dynamically bound (run-time bind), and the function life cycle (life recycle) modified by the two is not the same.
How to refer to the member of the same name of the parent class in the case of multiple inheritance?
In the case of re-inheritance, if multiple base classes have members with the same name, the reference method is:
PDeriveObj- > BaseClass1::Member
XVI. Operator overloading
Syntax:
Type Type::operator + (const Type & I) {}
17. Youyuan
Friends can provide external access to private and protected members. There are two implementations:
(1) friend function. Syntax: add friend before the function declaration. The friend function is not a member function of the class, and the function body is implemented or the function is called without ClassName::.
(2) friend class. Add: friend class VisitorClass to the declaration of the class
Friends are not inherited by subclasses.
XVIII. Template
Function template
Implementation syntax:
Add template (typename is equivalent to class) before the declaration and implementation of the function, which can be written on one line or divided into two lines. Note that there is no semicolon after >. If the declaration and implementation are written separately, write template in both places.
(1) declare and implement the function at the same time in one line of code
Template void func (T T1, T T2)
{...}
(2) declare and implement the function in two lines of code
Template
Void func (T T1, T T2)
{...}
(3) declare and implement the function in two places respectively
Template
Void func (T T1, T T2)
...
Template
Void func (T T1, T T2)
{...}
Reference syntax:
Func (5,6)
Class template
Declaration method:
A class template can implement a member variable of a common type in a class.
Template class ClassName
{public:
T * m_pVariable
}
Reference method:
ClassName obj
Template specialization
Template specialization can define special behavior for a particular data type. The definition of the class must be exactly the same as the general template class, except for using special syntax, changing T to a specific type, and defining special behavior.
Template class {define general functions, define special functions}
Define default values for templates
Template / / has a default value.
Parameter values of the template
In addition to template parameters preceded by keywords class or typename to indicate a common type, function templates and class templates can also contain other parameters that do not represent a type, such as a constant, which are usually basic data types.
Type conversion and C++ advanced type conversion
The basic type of strong turn can be written in two ways:
Int i; float f = 3.14; I = (int) f; I = int (f)
Advanced type conversion
The ANSI-C++ standard defines four new type conversion operators: reinterpret_cast, static_cast, dynamic_cast, and const_cast.
Reinterpret_cast can convert a pointer to any other type of pointer.
ClassA* pa
ClassB* pb=reinterpret_castpa
Static_cast can perform all type conversions that can be implicitly performed, as well as their reverse operations (even if such directional operations are not allowed to be implicitly performed). A pointer to a class, that is, it allows the pointer of an extended class to be converted to its base class type (this is a valid conversion that can be implicitly performed), as well as the opposite conversion: converting a base class to an extended class type. It does not check whether the converted base class is really entirely of the target type.
Derive* pa
Super* pb
Pa = static_cast pb
Pb = static_cast pa
In addition to manipulating class pointers, static_cast can also be used to perform conversions that are clearly defined in the class, as well as standard conversions for basic types:
Double dudes 3.14159265
Int I = static_cast (d)
Dynamic_cast is completely used for pointer manipulation. It can be used to perform any implicit conversion operations and they can be used for direction operations in the case of polymorphic classes. Unlike static_cast, however, dynamic_cast checks whether the operation in the latter case is legal, that is, it checks whether the type conversion operation returns a valid complete object of the required type.
In illegal cases, if used for pointers, NULL; will be returned. If used for references, an exception will be thrown.
Derive* pa = new Derive ()
Super* pb = new Super ()
Pa = dynamic_cast pb; / / failed. Return NULL
Pb = dynamic_cast pa; / / successful
The const_cast type conversion sets or cancels the constant const.
Class C {}
Const C * a = new C
C * b = const_cast (a)
Typeid (object_pointer)
This operator returns a pointer to a constant object of type type_info, which is defined in the standard header function. Type_info::name () returns the class name of the object.
21, namespace
Define a namespace:
Namespace ns1 {...}
Set the default namespace:
Using namespace ns1
Types that reference other namespaces:
Ns2::variable = xx
22, preprocessing command
# undef does the opposite of # define by undefining the macro definition of the parameters passed in
# ifdef, # ifndef, # if, # endif, # else and # elif
The directive # line gives us control over these two points, that is, displaying the number of lines in the file and the file name we want to display when something goes wrong. Its format is:
# line number "filename"
The following code will generate an error that is displayed in the file "assigning variable", line 1.
# line 1 "assigning variable"
Int a?
This directive interrupts the compilation process and returns the error message defined in a parameter
# error
This directive is used to configure the compiler, depending on the platform and compiler you are using.
# pragma
23. Predefined macros
An integer value of _ _ LINE__ that represents the number of lines currently being compiled in the source file.
The _ _ FILE__ string that represents the file name of the source file being compiled.
_ _ DATE__ A string of the format "Mmm dd yyyy" that stores the date when the compilation started.
_ _ TIME__ A string of the format "hh:mm:ss" that stores the time when the compilation starts.
The _ _ cplusplus integer value, which is defined by all C++ compilers as a value. If the compiler is fully compliant with the C++ standard, its value should be equal to or greater than 199711L, depending on which version of the standard it conforms to.
Thank you for reading! This is the end of this article on "what are the basic knowledge points of C++". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.