C ++ knowledge point

Source: Internet
Author: User

This is an article I saw on csdn.
The lecture is not bad. I will post it for you to see.
1. When passing a pointer, we can use the pointer to modify the content it points externally. However, it is impossible to modify the object pointed to by the external pointer. For example, if an external pointer is passed to the function to allocate space, the pointer or pointer reference must be passed.

2. Char carry [10] = {0}; the compiler will set all the other things to 0;

3. When the return value of the function is const, the returned item cannot be left after it is indicated with the same type;

4. const int * I; int const * I; int * const I; the first two functions are the same, indicating that the content that I points to remains unchanged; the last one indicates that the address that the Pointer Points to remains unchanged, but the content is variable.

5. Const member functions in the class. It is defined as adding const after the prototype. Constant functions cannot modify any attributes of a class. But there are two ways to modify it.

A) {(myclass *) This-> member1 = values ;}

B) define a member as mutable to be modified by the constant function.

6. constants of the const type in the class cannot be used to define arrays in the class. The enum {one = 100; two = 2}; defined one and two are acceptable. In general, the allocation problem defined by Enum is: Enum A {L = 9, z}; at this time, the value of Z is 10.

7. The Int defined by const can be used to open up arrays. However, elements in the constant array defined by const cannot be used to define arrays.

8. Use sizeof to calculate the space of the variable. If it is an array, return by actual space; constant string (actually a variable opened in the static memory area) sizeof returns a value greater than the actual length. If it is a pointer, only the size of the pointer type is returned regardless of the space it points. If sizeof is used to calculate the row parameter of the function, even the Group returns only the size of a pointer of the relevant type.

9. For example, int iarray [] = {12,124,433}; the compiler automatically assigns the length of three elements to the iarray. The formula for calculating the number of element lengths is sizeof (iarray)/sizeof (* iarray ).

10. copy constructor: When the row parameter and the real parameter are combined, if it is a value transfer type of a complex object, call the copy constructor to generate a temporary object as the real parameter and exit the function, the temporary object is released by calling the destructor. When the returned value is a complex object, it also calls the copy constructor to assign values. In this case, the number of calls of constructor and destructor is not equal. The prototype of the copy constructor is a (A &), which can be reloaded in the class. (The default copy constructor uses the bit COPY method: the shallow COPY method does not copy the content pointed to by the pointer ).

11. Volatile variables tell the compiler that code optimization is not required for this variable. In multi-threaded applications, if we read a variable into the register, the time slice will expire and process other threads. When the processor is re-acquired, the volatile type will tell the processor, instead of directly processing the register data, you can re-read the data from the variable to the Register to prevent dirty data.

12. The class and struct have the same functions to a certain extent, except that the default members of the former are private, while those of the latter have a common lack of time-saving members. Therefore, class is not a required reserved word for C ++.

13. the C and C ++ compilers generate different identifiers for the same function name after compilation. Therefore, when referencing the C library file, you must use the extern "C" to tell the compiler, it is a C function that is compiled according to the C Rules. The standard header file we use has been processed.

14. # include "filename"; # include <FILENAME>: the former searches for files in the current directory. If the files cannot be found, the former searches for files in the path specified by the system, the latter can be found directly under the path specified by the system.

15. Static variables allocated anywhere have the same lifecycle as the primary process. The second definition of an existing static variable has no effect on the use of the variable, but its visible range is only within the defined range. (The postgraduate entrance exam made a mistake !) (It is not difficult to understand the characteristics of static variables. The static type in the class is shared by all objects)

16. The implementation of inline functions is similar to that of macros. When an inline function appears, expand the function to avoid the function calling from the stack, such as the stack, and improve the efficiency. But the cost of inline functions is: The Code increases. Inline functions are suitable for member functions and free functions. The functions implemented in the class are automatically inline functions. Inline must be defined on The Implementation of The function. For example, inline int plusone (INT) is invalid. A friend function is automatically implemented as an inline function in the class body.

17. # include <iostream. h>

# Define debug (x) cout <# X "=" <x <Endl

# X indicates that X is output as a string.

18. Assert (0! = 0); if the condition in assert is false, the program is exited during running and the row number of the error code is reported. (# Include <assert. h>)

19. The static object calls its own destructor only when main ends or exit () is called. This means that it is very dangerous to call exit () in the destructor of an object and may enter an endless loop. Call abort () to exit the function. The static object destructor will not be called. We can use atexit () to specify the operations to be performed when jumping out of main or calling exit. Functions registered with atexit can be called before the destructor of all objects.

Void exit_fn2 (void)

{

Printf ("exit function #2 called/N ");

} // Processing functions

Atexit (exit_fn2 );

20. global variables actually use static storage. The construction of static variables is called before entering main, and its destructor is called at the end of main. Variable names are defined in a small scope (C ++ ):

// *. Cpp

Int A; // static variable, but extern int A; that is, it is global and externally visible

Static int B; // static variable. The opposite is static and extern, which is only valid in *. cpp and invisible to other units (files. The function definition is the same as above.

Main ()

{}

The static member variables of the class can be assigned the following values: int X: S = 23; (in *. cpp, both public and private can be used)

21. namespace: Define a namespace, and then use unsing to convert the current type context to the location specified by the namespace.

Namespace math

{

Enum sign {positive, negative };

Class INTEGER {

Int I;

Sign S;

Public:

Interger (INT I = 0): I (I ){.........}

Sign sign (){.........}

.......................

}; // End class

Interger A, B, C;

Interger divide (interger, interger );

} // No;

 

Void Q ()

{

Using namespace math;

Interger A; // hides Math:

A. Sign (negative );

Math: A. Sign (positive );

}

22. Generally, for the flaot F (int A, int B) function, some C ++ compilers generate the name of _ f_int_int after compilation, and some C compilers generate the name of _ F. Therefore, when linking C library functions in C ++, use extern "C" to tell the compiler to compile functions according to the C Rules. Similar to extern "C" {# include "myhead. h"}, C ++ also supports extern "C ++ "{}.

23. When calling a function, passing a reference also forces the pointer to the stack.

24. The order in which constructor, destructor, value assignment constructor, and overloaded = are called: (all three functions have been implemented)

A) x; x a = X;

Result:

X: Construct

X: copy_struct

B) x; X A; A = X;

Result:

X: Construct

X: Construct

X: copy_stru

Operator =

X: destruct

If no constructor is assigned, the result is:

X: Construct

X: Construct

Operator =

X: destruct

(If x a = x directly, do not use a General constructor to call the copy constructor)

Pointer to the member function of the class: Set int X: A (void ){}

X;

INT (X: * PF) (void) = & X:;

(X. * PF )();

Pointer to the member variable: Set int I; to the member variable of X

Int X: * PM = & X: I;

X;
X. * PM = 12;

X * P = & X;

P-> * PM = 11;

25. ++ Operator Overloading

Const X & operator ++ () // ++ B; const x operator ++ (INT) // B ++

The second parameter is a dummy and never used.

26. Automatic type conversion

A.) Class One {B} Class Two {

Public: One () {} public: Two (const one &){}

};};

Void F (two ){}

Main () {one; F (one );}

In this case, a constructor in two is called to perform automatic type conversion. However, the efficiency is not high. This prevents implicit type conversion. The method is as follows:

Class Two {public: explicit two (const one &){}};

Explicit only applies to constructors. In this case, you must call the function f (two (one ));

27. An Ideal string class that knows how to convert from string to char *:

Class string

{

PRIVATE: char * s;

Public:

String (const char * s = "")

{

S = new char [strlen (s) + 1];

Strcpy (S, S );

}

~ String () {Delete s ;}

Operator const char * () const {return s ;}

};

Int main (void)

{

String str1 ("lizhihui2 ");

String str2 ("lizhihui2 ");

Strcmp (str1, str2 );

}

28. If there are multiple conversion methods from one type to another, an error occurs:

Classs y;

Class X

{

Public: Operator y () const; // convert X to Y

};

Class y {

Public: Y (x); // convert X to Y

};

Void f (y );

Main ()

{

X;

F (x); // error: ambiguous Conversion

}

29. delete an array object:

Foo * fp = new Foo [100]; Delete [] FP; or delete [100] FP;

Make the pointer more like an array: int * const q = new int [10]; so that Q cannot be moved, it is more like an array.

30. New abnormal processor function when heap memory is used up

Void out_of_memory () {printf ("out of memory! /N "); exit (1 );}

Main () {set_new_handler (out_of_memory );................}

31. A global overload method for new and delete

Void * operator new (size_t sz)

{

Printf ("operator New: % d Bytes/N", SZ );

Void * m = malloc (sz );

If (! M) puts ("out of memory/N ");

Return m;

}

Void operator Delete (void * m)

{

Puts ("operator Delete./N ");

Free (m );

}

Class S

{

Int I [100];

Public:

S () {puts ("s: S ()");}

~ S () {puts ("s ::~ S ()");}

};

Int main (INT argc, char * argv [])

{

Int * P = new int (23); // operator New: 4 bytes

Delete P; // operator Delete.

 

S * PP = new S; // operator New: 400 bytes

Delete pp; // operator Delete.

 

S * pA = new s [3]; // operator New: 1208 bytes, more 8 bytes for Array info

Delete [] Pa; // operator Delete. (C ++ bilder unsupport)

Return 0;

}

The default new and delete systems call malloc and free to work. The system must maintain a memory allocation table. Remember the size and starting address of the allocated memory. Release the memory based on the starting address.

32. Reload the new feature to allocate space on the specified memory.

Class S

{

Int I;

Public:

S (int ix = 0) {I = IX ;}

~ S () {puts ("s ::~ S ()");}

Void * operator new (size_t D, void * LOC) {return LOC ;}

};

Int main (INT argc, char * argv [])

{

Int Len [10];

S * PS = new (LEN + 1) S (3412 );

// The first function is equivalent to telling New where to allocate space (implicit );

// Its value is the length to be allocated. Special Release is required for special allocation.

Return 0;

}

New allocates space on len to s objects. (The first parameter of the new overload must be size_t and the system will automatically pass it a size)

33. Jump functions setjmp and longjmp

Void Oz ()

{

Printf ("there's no placelike home/N ");

Longjmp (Kansas, 47 );

}

Jmp_buf Kansas;

Int main (INT argc, char * argv [])

{

If (setjmp (Kansas) = 0) Oz ();

Else printf ("I Have a Dream ../N ");

Return 0;

} // After the execution of Oz (), it will jump to printf ("I Have a Dream ../N") immediately; Execute

Setjmp () is a special function. When called, it stores information about the current process status in buff and returns 0; if longjmp is used for the same buff operation, it is like returning it from setjmp again, that is, the setjmp backend is correctly displayed. At this time, the return value is the second parameter for longjmp, so we can find that it is actually returned from longjum.

34. Exception customization and throw

Class up {};

Class fit {};

Void g ();

Void F (int I) Throw (up, fit)

{

Switch (I)

{

Case 1: Throw Up ();

Case 2: Throw fit ();

}
G ();

}

Void g () {Throw 47 ;}

Void my_unexpected ()

{

Printf ("unexpected handle! /N ");

Exit (1 );

}

Int main (INT argc, char * argv [])

{

Set_unexpected (my_unexpected );

For (INT I = 1; I <= 3; I ++)

{

Try {f (I );}

Catch (up) {printf ("Catch up/N ");}

Catch (FIT) {printf ("catch fit/N ");}

}

Return 0;

}

Set_unexpected is used to handle exceptions that are not recognized by the system (interrupted by default). The installer for exception handling points to terminate () by default ()). We have defined the up and fit exception throws and thrown them to capture them. An exception object is also generated when an exception is thrown. Catch (...) {} Catch all exceptions. (But the intercepted exception type is lost)

35. When an uncaptured exception occurs, the system calls terminate () by default. It calls the abort () function to exit directly from the process. At this time, the destructor of the static global variable is not called. You can use set_terminate to install your own terminate function. The usage is the same as that of the above installation. The returned typedef void (* terminate_handler) (); is the old processor pointer.

When a constructor allocates resources, if a unexpect exception occurs, the system ends without calling the destructor to release the allocated heap memory.

36. Run-Time type identification (rtti)

A.) compiler implementation.

Use the function typeid (objname). Name () to obtain the function name. In fact, typeid () returns a reference to a constant object of the global typeinfo class. Use before to determine whether an object is defined before another object.

Fit ft;

Up U;

If (typeid (FT). Before (typeid (u) printf ("lzh/N"); // is true

B) Security Method downward ing

C * Pc = dynamic_cast <C *> (PD); // OK: C is a direct base class
// PC points to C subobject of PD
When determining PD, it is not a C * type object. If yes, a pointer is returned. Otherwise, null is returned. It is determined by trying to assign a pointer, which is different from the first method.

 

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.