C ++ programming skills

Source: Internet
Author: User

C ++Language is an object-oriented language. The code written in C ++ is simpler, more efficient, and more maintainability and reusable. However, many people use the C ++ language but feel that C ++ is no different from C programming. This is actually caused by insufficient understanding and use of the features and features of the C ++ language. In fact, no programmer can use C language to program more efficiently than C ++.

1. Use new and delete for dynamic memory allocation and release

The new and delete operators are new operators in C ++. They provide dynamic storage allocation and release functions. It is equivalent to the C language functions malloc) and free), but the performance is superior. Using new has the following advantages:

1) new automatically calculates the size of the type to be allocated. It is easier to avoid errors without using the sizeof operator.

2) It automatically returns the correct pointer type, and does not require forced pointer type conversion.

3) You can use new to initialize the allocated object.

Example:

 
 
  1. 1), int * p;
  2. P = new int [10]; // assign an integer array containing 10 Integers
  3. Delete [] p; // delete this array
  4. 2) int * p;
  5. P = new int 100); // dynamically allocates an integer and initializes it.

2. Replacing macro calls with inline functions

For frequently-used functions, we recommend that you use macro calls in C language instead of function calls to accelerate code execution and reduce call overhead. However, macro calls have many drawbacks and may cause undesirable side effects.

For example, MACRO:

 
 
  1. #define absa) a)<0?-a):a)) 

When absI ++ is used, this macro will fail. Therefore, the inline function should be used in C ++ to replace macro call, so as to achieve the macro call function and avoid the disadvantages of macro call. To use an inlian function, you only need to place the inline keyword before the return type of the function. For example:

 
 
  1. Inline int Addint a, int B); // declare Add) as the inner function

In this way, when the compiler encounters an Add) function, it does not call the function, but directly embeds the function code to speed up program execution.

Iii. Use Function Overloading

In C, the names of the two functions cannot be the same; otherwise, compilation errors may occur. In C ++, two functions with the same function name and different parameters are interpreted as overload.

For example:

 
 
  1. Void PutHz (char * str); // output Chinese characters at the current position
  2. Void PutHz (int x, int y, char * str); // output Chinese characters at x and y

Function overloading helps programmers cope with more complexity, avoiding complicated function names such as intabs, fabs, and dabs. In large programs, makes the function name easy to manage and use, without the need to handle the function name.

4. Use reference instead of pointer for parameter passing

In C, if a function needs to modify the variable value used as a parameter, the parameter should be declared as a pointer type. For example:

 
 
  1. void Add(int *a) {(*a)++;}  

However, for complex programs, the use of pointers is prone to errors, and the program is hard to understand. In C ++, you can use references to replace pointers in the preceding cases to make the program clearer and easier to understand. A reference is an alias for a variable. operations on a reference are equivalent to operations on the original variable. For example, the referenced function is defined:
Void Add (int & a) (a ++); // The function referenced by a given integer is the same as that of the previous function using the pointer, however, the Code is simpler and clearer.

5. Use default parameters

In C ++, the function can use the default parameter, for example:

 
 
  1. void PutHzxy(char *str,int x=-1,int y=-1)  
  2. { if (x==-1) x=wherex(); if (y==-1) y=wherey(); moveto(x,y)  
  3. PutHz(str);}  

You can call the PutHzxy function in two ways. For example:

 
 
  1. PutHzxy ("C ++ language"); // use the default parameter and output it at the current position
  2. PutHzxy ("C ++ language",); // no default parameter is used

In general, a function should be as flexible as possible, using default parameters provides an effective way for programmers to deal with greater complexity and flexibility. Therefore, a large number of default parameters are used in C ++ code. It must be noted that all default parameters must appear on the right of non-default parameters. That is, once you start to define the parameter for taking the default value, non-default parameters are not described.

For example:

 
 
  1. Void PutHzxy (char * str, int x =-1, int y =-1); // correct
  2. Void PutHzxy (int x =-1, int y =-1, char * str); // Error

6. Use "class" to seal data

C language is a modular programming language, which implements certain data encapsulation functions through the use of functions and the independent compilation of files. However, C ++ is better at data encapsulation and inheritance than C by using the powerful functions of "classes. By using the "class" to encapsulate the data and all the operations on the data, a well-defined interface is established, this allows programmers to focus only on the use of a class without worrying about its implementation.

Because functions can encapsulate data to a certain extent, it is difficult for beginners of C ++ to grasp when to use functions and when to use classes when writing C ++ programs. Based on my experience, the following methods are summarized for the use of functions and classes: first, the functions to be completed by the program are divided into many basic sub-processes, A sub-process provides a relatively complete function. Then divide the data according to the following rules:

1) if some data is used by more than two sub-processes at the same time, the data and these sub-processes should be encapsulated using "classes.

2) if some data is used by only one sub-process, the data and the sub-process should be combined into a function. The data is declared as internal temporary data for this function.

3) if some data is used several times by a sub-process at different times, the data and the sub-process should be combined into a function. The data is defined as the internal static data of this function.

4) if the functions of a sub-process may be modified or extended in the future, the sub-process and the number used should be merged into a class, in this way, you can use an inherited method to modify and expand its functions in the future.

5) when 2), 3), and 4) are in conflict, 4) shall prevail.

For example, a program that uses the mouse in C ++ contains more than 10 sub-processes, such as MouseOpen) and MouseHide. If it is implemented by calling a H interrupt of DOS, because there is no commonly used data between sub-processes in the program, each sub-process should be defined as a function.

For example, if a data structure is defined to represent a graph, the image must be zoomed in, moved, rotated, and so on. Because all these sub-processes use public graphical data, we should define these sub-processes and the graphic data as a class.

VII. Use templates and BIDS

Borland C ++ 3.1 also introduces the template function. The powerful BIDSBorland International Data Structures is implemented through the Borland C ++ 3.1 template ). With BIDS, data structures such as arrays, linked lists, spine stacks, and queues of any data types can be stored without programming.

The following example implements a stack for storing integer variables:

 
 
  1. Typedef BI_StackAsVector <int> intstack;
  2. Main ()
  3. {Instack is; // defines the stack for an integer variable (int I = 0; I <10; I ++) is. push (I); // 10 Number of pressure stacks for (I = 0; I <10; I ++)
  4. Cout <is. ppop () <end1; // 10 output stacks
  5. }

The stack can be operated through the statement is. push), is. pop. For use of BIDS, refer to Borland c ++ 3.0 programmer reference.

This article takes Borland C ++ 3.1 as the background, but applies to most C ++ compilers.

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.