Read the essence of C and C ++ code-Translated by Dong Huiying, Chunk Allison

Source: Internet
Author: User
Tags bitset mathematical functions time and date
Chapter 3 Better C
    • C ++ is a type Security Language
    • All functions must be declared or defined before they are used for the first time.
    • Reference parameters directly support Reference call Semantics
    • The template allows you to create common functions.
    • Inline Functions combine the efficiency of macros similar to functions with the security of actual functions.
    • Declarations can appear anywhere in a function.
Chapter 2 pointer
    • C and C ++ are just as dangerous as those who use them.
    • Pointer is address
    • You can assign a value to any pointer as void *
    • Note that a const pointer and a pointer pointing to the const are distinguished.
    • P + n = (char *) P + N * sizeof (* P)
    • * (A + I) = A [I]
    • Unless in the context of sizeof and &, an array name is a pointer to its first element.
    • No multi-dimensional array, only Arrays
    • Only the existence of a pointer does not require the effectiveness of the implementation of the type it references (this is an incomplete type)

If you understand these concepts, you are gradually becoming a trusted c ++ProgramMember.

Chapter 4 pre-processor
    • The Preprocessor cannot understand the language.
    • Is the header not necessarily a file? (Not understood)
    • Remember the macro with parentheses
    • I would rather use inline functions than class function macros (except for string-based and tag-based pasting)
    • We would rather use a constant value than a macro of A Class Object.
    • Use an Assert macro to capture unexpected Conceptual errors
    • Use special macros to compile header files with conditions (to avoid loop inclusion)
    • C and C ++ support a three-character combination for international keyboards. c ++ supports more double-character and other reserved characters.
Chapter 2 one of the C standard libraries: for qualified programmers
    • <Ctype. h> character processing, isupper (C), tolower (),...
    • <Stdio. h> input and output, including formatting functions, character I/O functions, and file functions
    • <Stdlib. h> the complex tool contains the div_t {quot operator, Rem remainder} returned by the DIV function. The long integer is ldiv_t.
    • <String. h> text processing, copying, linking, comparing, and searching
Chapter 2 C standard library II: for skilled programmers
    • <Assert. h> support assertion of protected programs
    • <Limits. h> system parameters of integer calculation
    • <Stddef. h> common type and constant, including wide character wchar_t
    • <Time. h> time processing
Chapter 2 C standard library II: for excellent programmers
    • <Errno. h> Error Detection
    • <Float. h> system parameters of real number operations
    • <Locale. h> adaptive Culture
    • <Math. h> mathematical functions
    • <Setjmp. h> non-local branch
    • <Signal. h> interrupt handling
    • <Stdarg. h> variable length parameter table
Chapter 2 Abstraction
    • Complexity is an inevitable fact in life.
    • Abstraction is a tool for processing complexity.
    • Clear abstract data types can be defined to separate interfaces from implementations.
    • C ++ supports data abstraction
    • The member access control qualifiers (private and protected) Support encapsulation.
    • The specific types should include well-defined constructor, copy constructor, and assign value operator.
    • Operator overloading can make the behavior of a specific type similar to the built-in type
    • Template supports type Abstraction
    • Virtual functions support function Abstraction

Date class

 //  Date. h  # Ifndef date_h  # Define Date_h # Include <Iostream> Using  STD: ostream;  Struct  Daterep;  Class Date {  Public  : Date (  Int , Int , Int  ); ~ Date ();  Char * Format ( Char *) Const  ;  Int Compare ( Const Date &) Const ; Friend ostream & Operator <(Ostream &, Const Date & );  Private  :  Struct Daterep * Drep;  Static   Const   Char * Month_text [ 13  ] ;};  # Endif 
 // Date. cpp # Include <stdio. h> # Include  "  Date. h  "  Struct  Daterep {daterep (  Int , Int , Int  );  Private  : Friend  Struct  Date; friend ostream &Operator <(Ostream &, Const Date & );  Int  Month;  Int  Day;  Int  Year ;};  Const   Char * Date: month_text [ 13 ] = {  "  Bad month  " , "  January  " , "  February  " , "  March  " , "  Else l  "  ,  "  May  " , " June  " , "  July  " , "  August  " , "  September  "  ,  "  October  " , "  November " , "  December  "  }; Daterep: daterep (  Int M, Int D, Int  Y): Month (M), Day (D), Year (y) {} Date: Date (  Int M, Int D, Int  Y) {drep = New  Daterep (M, D, Y);} Date :: ~ Date () {Delete drep ;}  Char * Date: Format ( Char * BUF) Const  {Sprintf (BUF,  "  % S % d, % d  "  , Month_text [drep -> Month], drep -> Day, drep-> Year );  Return  Buf ;}  Int Date: Compare (Const Date & dp2) Const  {  Int Result = drep-> year-dp2.drep-> Year;  If (Result = 0  ) Result = Drep-> month-dp2.drep-> Month;  If (Result = 0  ) Result = Drep-> day-dp2.drep-> Day; Return  Result;} ostream & Operator <(Ostream & OS, Const Date & D) {OS <Date: month_text [D. drep-> Month] < '   ' <D. drep-> Day < "  ,  " <D. drep-> Year; Return  OS ;} 
 //  Tdate. cpp # Include <iostream> # Include  "  Date. h  "  Using   Namespace  STD;  Int  Main () {date D1 (  10 , 1 , 1951 ), D2 (3 , 7 , 1995  ); Cout < "  D1 =  " <D1 < Endl; cout < "  D2 =  " <D2 < Endl;  Return   0  ;} 

Chapter 4 Operations
    • Bit Operations Support System Programming and reduce memory needs
    • The bitwise operator allows access to the subset of the integer (but pay attention to the priority of the operator)
    • Bitset templates support effective bit setting with a fixed size
    • Vector <bool> template specifications support dynamic size bitwise strings
Chapter 2 forced type conversion of Type Conversion Box
    • C and C ++ provide implicit conversions to simplify mixed mode operations
    • In the operation, the integer type can be upgraded as needed.
    • Floating point operations are balanced by standard type conversion"
    • Function prototype helps the compiler provide implicit type conversion
    • Sometimes you do not want implicit conversions of user-defined types
    • To shield implicit type conversion, You can explicitly declare constructors with a single parameter.
    • Forced type conversion makes the type conversion clearer
    • Use forced type conversion in the function style as much as possible, instead of forced type conversion in the C style
    • Use the forced type conversion of the new style when applicable (that is, it is always used except when using the constructor call)
    • Use const whenever possible
    • Preference for semantic constants rather than bit logical Constants
    • Variable storage classes make removing const unnecessary in most cases
    • Rtti allows secure downward forced type conversion
Chapter 2 Visibility
    • In the C ++ file: extern "C" F (); tells the compiler to generate a connection name based on C's rules
    • Identifiers can have external connections (visible within multiple translation units), internal connections (visible only in separate translation units), and no connections
    • Objects with external connections must be defined in a named namespace (including a globally named namespace with a secret name)
Chapter 2 Control Structure
    • Display unchanged conditions with assertions or comments
    • Break exits the closed loop or branch
    • Continue jumps to the next iteration of the last closed loop.
    • Use the setjmp/longjmp mechanism to return results alternately under abnormal conditions
    • Capture synchronous and asynchronous signals using signal processing programs
Chapter 2 exceptions
  • Error Handling Method

    1. Ignore errors
    2. Check returnCode
    3. Use non-local redirection to change the direction of the execution process
    4. Usage exception
  • Exception Handling is a runtime Mechanism
  • C ++ exception handling is designed around the interrupt mode
  • Standard exception
    • Exception

      • Logic_error

        • Domain_error
        • Invalid_argument
        • Length_error
        • Out_of_range
      • Runtime_error
        • Range_error
        • Overflow_error
        • Underflow_error
      • Bad_alloc
      • Bad_cast
      • Bad_exception
      • Bad_typeid
  • "Resource allocation is initialization" Principle
  • One of the purposes of adding exceptions to a language is to make up for the deficiency of the constructor's no return value.
  • Throws an exception for errors that cannot be processed locally, including invalid parameters.
  • Do not use setjmp and longjmp before constructors and destructor objects. Instead, use an exception. When an object is thrown, all automatic objects in the stack are automatically destroyed.
  • Exceptions allow independent program components to communicate with each other about error conditions
  • Select the handler by matching the type of the thrown object
  • Arrange adjacent handlers according to the processing type from the most special to the most common order
  • If you use a standard library, you are prepared to capture exceptions (at least exceptions) in the standard inheritance structure)
  • Encapsulate Resource Allocation in automatic objects to ensure that the Destructor is called as needed
  • Encapsulate the results of the new expression in auto_ptr to ensure that the Destructor can be called properly.
  • You can use the exception specification for the document and enhance the exception types thrown by functions.
  • Assertions are only used to prevent your (quick Developer) errors.
  • Define an exception class for each component derived from the exception class (or runtime_error or logic_error, if it is a sum)
Chapter 2 Object-Oriented Programming
    • Three elements: encapsulation, inheritance, Polymorphism
    • A total of inheritance indicates the "is-a" relationship between the base class and the derived class.
    • The pointer to the base class can also point to the object of the derived class. The object of the derived class can always replace the base class object.
    • Polymorphism means that associated implementations share a single interface, which can be automated as needed as the included object type changes. C ++ supports polymorphism through virtual functions
    • The virtual function simulates dynamic binding through the function finger table.
Chapter 2 Algorithm
    • Algorithm types: general sequence algorithms, sorting algorithms, and numerical algorithms. The first two algorithms are included in <algorithm> and the numerical algorithms are included in <numeric>.
    • Algorithms are the "elements" of computer science"
    • The algorithms in the C ++ standard library are function templates, and most of them are processing a series of objects in the range defined by [begin, end ).
    • Function objects are instances of classes that define operators.
    • The modifiable function object contains the definition of its parameters and return value types.
    • Determines whether a function or function object of the bool type is returned.
    • The function Object Adapter is a function template that uses one or more function objects and other optional values as parameters and returns a new function object.
    • You can customize algorithm assertions by combining function objects with function object adapters. Generally, you do not need to write functions by yourself.
Chapter 4 containers and iterators
    • Standard containers support any specific type of objects, including other containers. The specific type is a type with value semantics, meaning that they can be copied, assigned, and compared to equal or unequal
    • Standard containers include: basic sequence containers, container adapters, and associated containers
    • Basic sequence containers include vectors, double-ended columns, and tables. The differences between them are mainly about where to allow effective insertion and deletion of elements, and the iterator they support.
    • An iterator is a generalization of pointers, and an iterator is a binder that connects algorithms and containers in a common way.
    • There are five types of iterators: Input iterator, output iterator, forward iterator, two-way iterator, and random access iterator.
    • Containers of iterators that do not support algorithms often require defining their own panels (for example, list <t> sort ())
    • Container adapters include stack, queue, and priority queue. Container adapters use stricter interfaces to encapsulate basic sequences for more advanced data abstraction.
    • Associated containers include: Set, multi-set, graph, and multi-repeated graph. The associated Container set and graph only store unique keywords.
    • Special-purpose containers bitset and valarray do not support containers supported by other standard containers -- iterators -- algorithm topics
Chapter 4 & 18 Text Processing
    • It is a good habit to read a row in an interactive application and parse each row whenever necessary.
    • The most important feature of the Standard C ++ string class is memory management.
    • The standard C ++ Library supports any "class character type" string through the template basic_string
    • If the standard library cannot meet the file processing needs, try POSIX file operations. If not, separate the platform-dependent code in an independent module to facilitate the port process.
    • Always consider using C ++ to encapsulate low-level concepts and operations
Chapter 1 time and date Processing
    • Perform simple time and date operations using functions in <time. h>, such as localtime, strftime, and difftime.
    • Be sure to know the reference date of the Environment
Chapter 4 dynamic memory management
  • Distinguish between shallow copy and deep copy
  • Reload new and delete:
      • The standard C ++ library defines 12 functions for allocating and releasing memory. When the new operator is used, it calculates the required bytes and then calls one of these functions in order to allocate these bytes. The 12 functions are:
        • Void * operator new (size_t); // scalar form
        • Void * operator new (size_t, const nothrow_t );
        • Void * operator Delete (void *);
        • Void * operator Delete (void *, const nothrow_t );
        • Void * operator new [] (size_t); // array format
        • Void * operator new [] (size_t, const nothrow_t );
        • Void * operator Delete [] (void *);
        • Void * operator Delete [] (void *, const nothrow_t );
        • Void * operator new (size_t, void *); // configure new
        • Void * operator new [] (size_t, void *);
        • Void * operator Delete (void *, void *);
        • Void * operator Delete [] (void *, void *);
  • Configure new
  • You can use dynamic memory when you do not know how much memory is needed to store an object or how many objects are needed.
  • The new operator calls operator new to allocate memory for a dynamic object, and then calls the appropriate constructor. The delete operator destroys the object by calling the object's destructor, and then calls operator Delete
  • Delete [] must be used for arrays.
  • Whenever a class is a pointer member, check whether deep copy is required.
  • Remember that the failure of memory operations will cause the bad_alloc exception.
  • Use the new configuration on the given address to build an object.
  • To minimize the number of memory fragments, you can allocate similar sets of dynamic objects to a dedicated memory pool, such as a container.
  • Whenever possible, let the standard library manage the memory for you

 

These knowledge points are excerpted from the Chinese version of C and C ++ code.

      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.