Comprehensive C ++ programming skills

Source: Internet
Author: User

C ++ 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 over using malloc:

(1) new automatically calculates the size of the type to be allocated without using the sizeof operator, which is easy to use and can avoid errors.

(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), int * p;

P = new int [10]; // assign an integer array containing 10 Integers

Delete [] p; // delete this array

(2) int * p;

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:

# Define abs (a) <0? (-A) :( a) when abs (I ++) 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 inline_function, you only need to put the inline keyword before the function return type. For example:

Inline int Add (int a, int B); // declare Add () as the inner function

In this way, the compiler does not call the Add () 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:

Void PutHz (char * str); // output Chinese characters at the current position

Void PutHz (int x, int y, char * str); // output Chinese characters at x and y

Using function overloading can help programmers deal with more complexity, avoiding complicated function names such as intabs (), fabs (), dabs () and so on. At the same time, 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:

Void Add (int * a) {(* a) ++ ;}

However, for complex programs, the use of pointers is easy to make mistakes, and the program is hard to understand. In C ++, you can use references to replace pointers in the above 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 ++); // a is an integer reference.

This function has the same functionality as the previous function using pointers, but the code is more concise and understandable.

5. Use default parameters

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

Void PutHzxy (char * str, int x =-1, int y =-1)

{If (x =-1) x = wherex ();

If (y =-1) y = wherey ();

Moveto (x, y)

PutHz (str);} can call the PutHzxy () function in two ways, for example:

PutHzxy ("C ++ language"); // use the default parameter and output it at the current position

PutHzxy ("C ++ language",); // a function should be as flexible as possible when no default parameter is used, using default parameters provides an effective way for programmers to handle 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, you cannot describe non-default parameters.

For example:

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

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 continuation than C by using the powerful functions of "class. 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 having to care 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 implements 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 the internal temporary data of 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, this allows you to modify and expand your functions in the future.

(5) When (2), (3), and (4) 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. For example, we call a H interrupt of DOS, because there is no commonly used data between sub-processes in the program, so we should define each sub-process as a function.

Another example is to define a data structure that represents a graph, which requires sub-processes such as enlargement, movement, and rotation. 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 to implement the powerful BIDS (Borland International Data StrUCtures) 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:

Typedef BI_StackAsVector intstack;

Main ()

{Instack is; // defines the stack of an integer variable.

For (int I = 0; I <10; I ++)

Is. push (I); // 10 stacks

For (I = 0; I <10; I ++)

Cout <}

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

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.