Basic design of C + + programming

Source: Internet
Author: User

C and C + + 's respective characteristics

C is a structured language that focuses on algorithms and data structures. The design of C program is the first consideration is how to pass the process, the input processing to get output. For C + +, first of all, consider how to build the object model, so that the model can fit with the corresponding problem domain, so that you can obtain the state information of the object to get output or implementation process control.

Ifndef/define/endif effect in header file

Prevents the header file from being repeatedly referenced.

C + + calls C. post-compilation functions plus extern C

C + + supports function overloading, whereas a function overload is not supported in the language. Functions are compiled in C + + and the names in the library differ from the C language. Assuming the function prototype is void foo(int i,int j) , the C language is compiled in the library after the name is _foo , and in the C + + compiled library name is _foo_int_int the name. C + + provides a connection interchange with a specified symbol to extern“C” resolve name matching issues.

Malloc/free and New/delete

malloc and free are the standard libraries of the C + + language, New/delete is the C + + operator. They can both apply and release memory dynamically. For objects of non-intrinsic data types, only malloc cannot meet the requirements of dynamic objects. When an object is created, the constructor is automatically executed, and the object executes the destructor automatically before it dies. Because Malloc/free is a library function and not an operator, the task of executing constructors and destructors cannot be imposed on malloc/free, not within the control of the compiler.

Differences in pointers and references
    • non-null difference: You cannot use a reference to a null value under any circumstances. A reference must always point to an object. The absence of a reference to a null value means that the referenced code is more efficient than using pointers.
    • legality difference: It is not necessary to detect its legitimacy before using a reference. The pointer is always detected to prevent it from being empty.
    • The difference can be modified: The pointer can be re-assigned to point to a different object, but the reference is always in the specified formation at initialization, and cannot be changed later, but its contents can be changed.
    • Application differences: You should use the pointer in the following cases: 1, there is a possibility of not pointing to any object (the pointer is set to NULL) 2, you need to be able to point to different objects at different points (change pointer pointing).
pointer functions and function pointers

pointer function: pointer function is a function with a pointer, that is, the essence is a function. A function return type is a pointer to a type. The function return value must be accepted with a pointer variable of the same type. Pointer functions must have function return values, and in the keynote function, the function return value must be assigned to a pointer variable of the same type.

类型标识符 *函数名(参数表)//int* f(int x,int y)    

Example

    int * GetDate(int wk,int dy);    main()    {        int wk,dy;        do        {            printf(Enter week(1-5)day(1-7)\n);            scanf(%d%d,&wk,&dy);        }        while(wk<1||wk>5||dy<1||dy>7);        printf(%d\n,*GetDate(wk,dy));    }    int * GetDate(int wk,int dy)    {        static int calendar[5][7]=        {           {1,2,3,4,5,6,7},           {8,9,10,11,12,13,14},           {15,16,17,18,19,20,21},           {22,23,24,25,26,27,28},           {29,30,31,-1}        };        return &calendar[wk-1][dy-1];    }

function pointer: The function pointer is a pointer variable to a function, which is essentially a pointer variable.

类型标识符 (*函数名)(参数表)//int (*f)(int x,int y)

A pointer to a function contains the address of the function, which can be used to invoke the function. Assigning a function address to a pointer can take the following two forms:

void (*fptr)();fptr=&Function;fptr=Function;

The FETCH address operator & is not required because a function identifier alone represents its address, and if it is a function call, it must also contain a parameter table enclosed in parentheses. There are two ways to invoke a function with pointers:

x=(*fptr)();x=fptr();

Example

    void (*funcp)();    void FileFunc(),EditFunc();    main()    {        funcp=FileFunc;        (*funcp)();        funcp=EditFunc;        (*funcp)();    }    void FileFunc()    {        printf(FileFunc\n);    }    void EditFunc()    {        printf(EditFunc\n);    }    程序输出为:        FileFunc        EditFunc

Reference Source: http://www.cnblogs.com/gmh915/archive/2010/06/11/1756067.html

32-bit machines with 64-bit machines
32位编译器:      char :1个字节      char*(即指针变量): 4个字节(32位的寻址空间是2^32, 即32个bit,也就是4个字节。同理64位编译器)      short int : 2个字节      int:  4个字节      unsigned int : 4个字节      float:  4个字节      double:   8个字节      long:   4个字节      long long:  8个字节      unsigned long:  4个字节64位编译器:      char :1个字节      char*(即指针变量): 8个字节      short int : 2个字节      int:  4个字节      unsigned int : 4个字节      float:  4个字节      double:   8个字节      long:   8个字节      long long:  8个字节      unsigned long:  8个字节
* and + + operator precedence

pointer=*P++Equivalent to the pointer=*P;P++; pointer=*++P equivalent ofP++;pointer=*P;

float value[] = {1,2,3,4,5};float *vp;vp = value;for (int i = 0; i < 5;++i)    cout << *vp++ << ", ";

The output of the program is 1,2,3,4,5, if modified to *++vp , the result is 2, 3, 4, 5, -1.07374e+008

pointer operations and Arrays

The memory allocation of the array a[] is on the stack and can be modified either by the array name or by pointers to the array. The following pointer p points to a literal constant area of the string, is not allowed to modify, so through the pointer to modify the error. However, you can use p[0] to access the appropriate element.

char a[]="hello";a[0]=‘x‘;char* q=a;q[0]=‘b‘;char *p="hello";//将字符串的首地址装入指针变量,而不是将整个字符装入指针变量p[0]=‘x‘;
pointer arrays and array pointers

Pointer array: array of pointers, which is used to store pointers to arrays, which are arrays of elements that are pointers

Array pointer: A pointer to an array, which is a pointer to the array

int* a[4] Pointer array

Expression: The elements in array A are INT-type pointers

Element representation: *a[i] *(a[i]) is the same, because [] precedence is higher than *

int (*a) [4] Array pointer

Represents: Pointer to array a

Element representation: (*A) [i]

Note: In practical applications, for pointer arrays, we often use this:

typedef int* pInt;pInt a[4];

Reference Source: http://www.cnblogs.com/Romi/archive/2012/01/10/2317898.html

application of pointer arithmetic in high-dimensional array

In fact, C + + does not provide high-dimensional array introspection. As an example of a two-dimensional array (int a[4][5]), a user-created two-dimensional array is actually an array of arrays for each element itself.

    • A: that is, a int(*)[5] a pointer to the No. 0 element of array a a[0], and A is a constant, no assignment operation, a+i the type is also the same int(*)[5] , pointing to a[i]; &a+1, Skip 4 rows and 5 columns for a total of 20 elements.
    • *a or a[0]: type is int* ,A is a pointer to the array a[0]* first element a[0][0].
    • * (a+1) or a[1]: type is int* , because the type of a is int (*) [5], that is, a points to a one-dimensional array with 5 elements, so a+1 skips 5 elements. That is, * (a+1) or a[1] is a pointer to the first element a[1][0] of the array a[1].
    • * (* (a+1) +2): type is int . (* (a+1) +2) is a pointer to the second element a[1][2] of the array a[1], which is a[1] the 2nd element of the group a[1][2] .

Summarize:

    • &a = = = Int (*) [4][5]
    • A+i = = Int (*) [5]
    • * (a+i) = = = = int*;
    • * (* (a+i) +j) =====int
    • * (A+i) =a[i];
    • * (* (a+i) +j) =* (a[i]+j) =a[i][j]

In the following program fragment

int a[]={1,2,3,4,5};int *ptr=(int*)(&a+1);cout<<*(ptr-1);//结果为5

Because the type of &a+1 is int (*) [5], it is not a+1. Therefore &a+1 causes the pointer to skip over the size of the entire array a (5 int size). The PTR is actually cast as & (A[5]), which is a+5, so ptr-1 points to the last element of array A. The output result is 5.

This pointer
    • The this pointer is essentially a function parameter, except that the compiler hides the formal, syntactic-level arguments. This can only be used in member functions and cannot be used by global functions or today's functions.
    • This is constructed before the member function is started and cleared after the member's end.
    • This pointer does not occupy the space of the object. This is equivalent to the argument of a non-static member function, which does not occupy the object space. It does not contain a relationship with the object, except that the object that is currently calling the function is pointing to it. The parameters of all member functions, whether implicit or not, do not occupy the space of the object, only occupy the stack space when the argument is passed, or directly occupy a register.
    • The this pointer is defined only in the member function. After you get an object, you cannot use the this pointer through the object. Therefore, we cannot know the position of the this pointer of an object (only the position of this pointer in the member function can be obtained by &this).
Static

The Static keyword action-the function body static variable is scoped to the function body, and unlike the auto variable, the memory of the variable can only be allocated once, so its value remains the last value at the next call. -Static global variables within a module can be accessed by all functions within the module, but not by other functions outside the module. -The static function within the module can only be called by other functions within the module, and the function's scope of use is limited to the module it declares. -The static member variable in the class belongs to the entire class and has only one copy of all objects of the class. -The static member function in the class belongs to the entire class, and the function does not receive the this pointer, so it can access only the static member variables of the class.

Object-oriented Basic concepts

Three principles of object-oriented design: encapsulation, inheritance, polymorphism

    • Open-close principle (opening and closing principle) is one of the important features of object-oriented design: Software is open to extensions and should be closed for modification.
    • Defensive programming (defensive programming) is just a programming technique that is independent of object-oriented design. The main idea is that the subroutine should not be corrupted by passing in the wrong data, even if it is the error data generated by other subroutines. The idea is to limit the impact of possible errors to a limited extent.
Virtual functions
    • virtual functions take the method of virtual invocation. a virtual call is a mechanism that works with only part of the information, specifically allowing us to invoke a function that knows only the interface and does not know its exact object type. However, if you want to create an object, you must know the exact type of the object, so the constructor cannot be virtual.
    • virtual functions are at a cost. because the objects of each virtual function must maintain a V-table, there is a overhead when using virtual functions. If you are only a small class and do not want to derive other classes, you do not need to use virtual functions at all.

The virtual function takes up a table entry in vtable and holds an instruction to jump to its entry address. When an object containing a virtual function is created, it attaches a pointer to its head and points to the corresponding position in the vtable. When a virtual function is called, no matter what the pointer is called, the entry address is found and executed according to Vtable, thus realizing "dynamic Union". Instead of simply jumping to a fixed address, as with a normal function.

Friend Yuan

A friend is a normal function that is defined outside the class, but it needs to be described in the class, and in order to distinguish it from the member functions of the class, the keyword friend is preceded by the description. The role of friends is to improve the efficiency of the program, but it destroys the encapsulation and concealment of the class, allowing non-member functions to access the private members of the class.

Virtual inheritance

Virtual inheritance occurs in order to resolve multiple inheritance.

Virtual pointer

A virtual pointer or virtual function pointer is the implementation detail of a virtual function. Each object in a class with a virtual function has a virtual pointer to the virtual function table for that class.

C + + extra overhead
    • compile-time overhead: new features such as templates, type hierarchies, strong type checking, and a large number of C + + templates and algorithm libraries that use these new features significantly increase the burden on the C + + compiler. However, it should be seen that these new skills significantly reduce the workload of the vast majority of C + + programmers without increasing the efficiency of program execution.
    • Run-time overhead:
      • Virtual base class
      • Virtual functions
      • RTTI (Runtime Type information) (Dynamic_cast and typeID)
      • Abnormal
      • Construction and destruction of objects

Basic design of C + + programming

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.