C ++ learning points

zhaozj2021-02-17  59

1. When the pointer is transmitted, we can modify the content points to the outside by pointer. However, if you want to modify the object pointing to the external pointer is not possible. For example, the external pointer to the function is transmitted to allocate space, and the pointer to the pointer or pointer must be passed.

2. Char carry [10] = {0}; compiler will set out all things thereafter;

3. When the function return value is const, the returned thing is paid to a type of identical indication, it cannot be left value;

4. Const int * i; int * const * i; int * const i; the first two functions are the same, indicating that the content points to which I is constant; the last description pointer points to the address constant, but the content varies.

5. Const member functions in the class. Defined as a CONST after prototype. Constant functions cannot modify any properties in the class. But there are two ways to modify.

a) {(myclass *) this-> member1 = values;}

b) Define a member to Mutable can be modified by a constant function.

6. The constant constant type in the class cannot be used in the class to define an array. ENUM {One = 100; TWO = 2}; defined one, TWO can be. Usually an ENUM defined setup problem: enum a {l = 9, z}; at this time, the value of Z is 10.

7. INT defined with const can be used to open an array, but the elements in the constant array definition cannot be used to define an array.

8. Calculate the space of the variable with the sizeOf, if it is an array, press the actual space to return; constant string (actually the variable opened in a static memory area) SIZEOF returns to the actual length plus one. If it is a pointer, it is not considered to point to the space size, and only returns the size of the pointer type. If you use the SizeOf to calculate the row ginseng, even if the group is also returns a size of a related type pointer.

9. If Int IaRray [] = {12, 124, 433}; the compiler will automatically assign the length of 3 elements to IARRAY. The number of element lengths is calculated as a sizeof (IARRAY) / SIZEOF (* IARRAY).

10. Copy constructor: When the collections and the actual parameters are combined, if it is the type of complex object, the calling constructor generates a temporary object as an argument, when the function is sent, the temporary object is called the destructor released. When the return value is a complex object, it is also a call copy constructor to assign a value. This will appear in cases where the constructor and the destructive function are not equal. The prototype of the copy constructor is A (A &), we can overload in the class. (The default copy constructor is a bit (bit) copy method: shallow copy, no copy of the pointer points to the content).

11. Volatile type variable tells the compiler that this variable does not need to be optimized. In multi-threaded applications, if we read a variable to the register, at this time, the time film expires, dealing with other threads, when re-obtaining the process, the Volatile type tells the process, and read data from the variable to the register. Instead of direct processing with register data, it can prevent dirty data.

12. Class and Struct have the same function to some extent, but the former default members are private, and the latter is common in the default. Therefore, the Class is not a reserved word 13 necessary for C . C and C compilers, different indications that are generated after compiling the same function name, so in that the extern "C" must be used to tell the compiler when referenced by the library file referenced, it is a function of C, compiles the rule of C. Usually we use the standard header files have been processed.

14. #Include "filename"; #include , the former is first looking for files in the current directory, if you can't find the path to the system specified, the latter is directly to the path specified by the system.

15. Static variables allocated anywhere, their life cycle and the main process are the same. The second time defines an existing STATIC variable, which has no effect on the variable, but its visible range is only within the defined range. (The postgraduate studies have made a mistake!) (It is not difficult to understand from the characteristics of static variables, and the Static type in the class is shared by all objects)

16. Inline function (inline) is similar to the actual and macro, where the function is expanded to avoid function call, such as stack, and improve efficiency. But the price of the inline function is: the code is increased. The inline function is suitable for member functions and free functions. The function implemented in the class is automatically inlined function. Inline must be defined to the implementation of functions, for example: Inline int plusone (int) is invalid. The friend function is automatically changed to the inline function in the body of the class.

17. #Include

#define debug (x) cout << # x "=" << x << Endl

The #x represents X is output as a string.

18. Assert (0! = 0); if the conditions in Assert are fake, the exit program is returned during the run, and the line number of the error code is reported. (#Include )

19. The static object calls its own destructor when the MAIN ends or exit () is called. This means that in order to call exit () in an object's destructor, it is possible to enter a dead cycle. Calling Abort () to exit the function, the destructor of the static object is not called. We can use ATEXIT () to specify the operation you want to perform when you jump out of the MAIN or call EXIT, and use the ATEXIT registration function to call the destructor's destructor.

Void exit_fn2 (void)

{

Printf ("EXIT FUNCTION # 2 Called / N");

} // handler

Atexit (exit_fn2);

20. The global variable actually uses static storage. The structure of the static variable is called before entering Main, and it calls its destructor. The name of the variable is made of small range (C ):

//*.cpp

INT A; // static variable, but for extern int a; 即 即 is global, external visible

Static int b; // static variables, STATIC and Ex Ex Ex Expern, only in * .cpp, it is invisible to other units (files). The definition of the function is the same. Main ()

{}

The static member variable of the class can be assigned the following: INT x :: S = 23; (in * .cpp, no matter how private privacy)

twenty one. Namespace: Define a namespace and use unsing to convert the current type context to the name space.

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

A.SIGN (Negative);

Math :: A.SIGN (POSTIVE);

}

22. Generally, for the function Flaot F (Int A, INT B); some C compiler compiles the name of _f_int_int, some C compiler generates the _f's name. Therefore, in the library function of the C , use externaln "c" to tell the compiler, press the rule to compile functions. Similar to extern "c" {# include "myhead.h"}, C also supports EXTERN "C " {}.

23. When the function is called, the pass reference is also a pointer stack.

24. Constructing function, destructuring function, assignment constructor, overloaded =, four call sequences of four: (three functions have been implemented)

a) x x; x a = x;

RESULT:

X: construct

X: Copy_Struct

b) x x; x a; a = x;

RESULT:

X: construct

X: construct

X: Copy_STRU

Operator =

X: destruct

If there is no assignment function, the result:

X: construct

X: construct

Operator =

X: destruct

(If you directly x a = x; this does not drop with the general constructor, call the copy constructor)

Pointer to the member function of the class: set int x :: A (void) {}

X x;

INT (x :: * pf) (void) = & x :: A;

(x. * pf) ();

Pointer to a member variable: set int i; is a member variable of X

INT x :: * PM = & x :: i;

X x;

x. * pm = 12;

X * p = & x;

P -> * pm = 11;

25. operator overload

Const X & Operator () // B; Const X Operator (int) // b

The second parameter is dummy, never use.

26. Automatic type conversion

a.) Class one {b} class two {public: one () {} public: two (const one ") {}

};

Void F (Two) {}

MAIN () {one one; f (one);}

The TWO is called automatic conversion in TWO. But the efficiency is not high. You can block an implicit type conversion. The method is as follows: Two is given

Class two {public: explicit two (const one "{};

Explicit only works on the constructor. The function must be called in this case: 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 is a variety of conversion methods from one type to another, it will be wrong:

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 x;

f (x); // error: Ambiguous Conversion

}

29. Delete array objects:

FOO * fp = new foo [100]; delete [] fp; or delete [100] fp;

Make pointers more like arrays: int * const Q = new int [10]; this Q cannot be moved more like an array.

30. NEW memory usage exception processor function

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 system New and Delete are working in Malloc and Free, and the system should maintain a memory allocation table. The assigned memory should remember its size and start addresses, and release the address based on the start of the address.

32. Overloading New in a specific memory allocation space

Class S

{

INT I;

PUBLIC:

s (int = 0) {i = ix;}

~ s () {PUTS ("s :: ~ s ()");}

Void * Operator new (size_t d, void * loc) {returno

}

Int main (int Argc, char * argv [])

{

INT LEN [10];

S * ps = new (len 1) s (3412);

// The first function is equivalent to telling the NEW where to start allocating space (implicit);

// It is the length to be assigned. Special assignments should be taken to take special release.

Return 0;

}

NEW allocates space to the S object on the space of the LEN. (NEW heavy load first parameter must be automatically transmitted to it to a size size for the size_t system)

33. Jump function setjmp, 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 performing oz (), you will immediately jump to Printf ("I have a dream ../ n"); execution

SetJMP () is a special function that is called when called, it is in BUFF and returns 0; if you use longjmp to the same buff, this is like returning from setjmp again. , The rear end of SetJMP is correctly popped up. At this time, the return value is the second parameter for longjmp, so it can be found that it is actually returned from longjum.

34. Abnormal customization and thrown

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 setting the abnormality that the processing system is not recognized (the default is interrupted) (the exception handler is default to Terminate ()). Above we defined UP, Fit two exceptions and throwing these two exceptions to capture. An exception is generated when throwing anomalies. Catch (...) {} captures all exceptions. (But lost an abnormal type of interception)

35. When there is an abnormality that is not captured, the system default call terminal (), which calls the Abort () function to exit directly from the process, at which time the destructor of the static global variable is not called. You can use Set_Terminate to install your Terminate function, the usage is the same as the above installation. He returned Typedef void (* terminate_handler) (); for the old processor pointer.

When a constructor is assigned a resource, if there is a unExPect exception to arrive, the system will end without calling the destructor to release the allocated heap memory.

36. Type determination during operation (Run-Time Type Identification, RTTI)

a.) Compiler implementation.

Use the function typeid (ObjName) .Name () to get the name of the function. In fact, TypeId () returns a reference to the constant object of the global TypeInfo class. Use Before to determine if an object is defined before another object.

Fit ft;

Up U;

IF (TypeID (ft))) Printf ("lzh / n"); // is true

b). Safety method to map down mapping

C * pc = Dynamic_CAST (pd); // OK: C Is A Direct Base Class

// PC Points to C Subobject of Pd

Determine the PD is not a C * type object, if returns a pointer, otherwise returns null. By trying to decide the method, it is different from the first method.

转载请注明原文地址:https://www.9cbs.com/read-28568.html

New Post(0)