Programming Tips for C + +

Source: Internet
Author: User

The C + + language is an object-oriented language, and code written in C + + is more streamlined, efficient, maintainable, and reusable. But many people use the C + + language and feel that C + + is no different from C programming. This is due to the features and features of the C + + language is not enough to understand and use. In fact, no programmer can use the C language more efficiently than the C + + language.

I. Dynamic memory allocation and deallocation using new and delete

The operator new and delete are new operators in C + + that provide the dynamic allocation and deallocation of storage. It functions like the C-language function malloc () and free (), but with superior performance. There are several advantages to using new than malloc ():

(1), new automatically calculates the size of the type to be allocated, do not use the sizeof operator, it is easier to avoid errors.

(2. It automatically returns the correct pointer type without forcing a pointer-type conversion.)

(3), the allocated object can be initialized with new.

Examples of Use:

(1), int *p;

P=new int[10];//Assign an array of 10 integers

Delete[] p;//delete this array

(2), int *p;

p=new Int (100);//dynamically assigns an integer and initializes

Second, using inline inline function instead of macro call

For frequently used functions, the C language recommends using a macro call instead of a function call to speed up code execution and reduce the call overhead. But macro calls have a number of drawbacks that can cause undesirable side effects. such as macros:

# define ABS (a) ((a) <0? (-a): (a), this macro will go wrong when using ABS (i++).

Therefore, in C + + should use inline inline function instead of macro invocation, so that the function of macro calls can be achieved, but also avoid the disadvantages of macro calls.

Using an inline function simply puts the inline keyword in front of the function return type. For example:

inline int Add (int a,int b);//Declare Add () as an inline function

This way, when the compiler encounters the Add () function, it does not make a function call, but embeds the function code directly to speed up the execution of the program.

Iii. using function overloading

In the C language, the names of two functions cannot be the same, or a compilation error will result. In C + +, two functions with the same function name and different parameters are interpreted as overloads. For example:

void Puthz (char *str); Output Kanji at current position

void Puthz (int x,int y,char *str); Output kanji at x, y

Using function overloading can help programmers cope with more complexity, avoiding the use of complex function names such as Intabs (), Fabs (), Dabs (), and, in large programs, making the names of functions easy to manage and use without racking their brains to handle function names.

Iv. using references (reference) instead of pointers for parameter passing

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

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

But for complex programs, using pointers is error-prone and programs are difficult to read. In C + +, references can be used in place of pointers to make the program more readable. A reference is an alias to a variable, and the reference is manipulated as if it were an existing variable. , such as a function defined with a reference:

void Add (int &a) (a++;);//a is a reference to an integer

This function is the same as the function of the previous function that uses pointers, but the code is more concise and understandable.

V. Using default parameters

In C + +, functions can use default parameters, such as:

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);}

There are two ways to call the function Puthzxy (), for example:

Puthzxy ("C + + language");//using default parameters, output at current position

Puthzxy ("C + + language", 10,10);//not using default parameters

Typically, a function should be as flexible as possible, and using default parameters provides an effective way for programmers to handle greater complexity and flexibility. As a result, the default parameters are used extensively in C + + code.

It is important to note that all default parameters must appear to the right of the default parameters. That is, once you start defining the parameters of the default values, you can no longer describe non-default parameters.

For example:

void Puthzxy (char *str,int x=-1,int y=-1); That's right

void Puthzxy (int x=-1,int y=-1,char *str);//Error

Vi. using "class" to seal the data

C language is a modular programming language, the use of functions and the individual compilation of files to achieve a certain data encapsulation function. But C + + uses the power of "class" to do a lot better than C in terms of data encapsulation, inheritance, and so on. By using "class" to encapsulate the data and all the operational collections of the data, a well-defined interface is established so that the programmer can use a class only to care about its use, rather than its implementation.

Since functions can also be implemented to a certain extent in the encapsulation of data, when writing C + + programs when using the function, when to use the class, for C + + beginners difficult to grasp. Based on the author's experience, the following methods are summed up for the use of functions and classes:

First, the function that the program needs to complete is divided into a lot of basic sub-processes, a sub-process to achieve a relatively complete function. It is then divided according to the following rules:

(1), if some data are used at the same time by more than two sub-processes, these data and these sub-procedures should be used "class" encapsulation.

(2), if some data is used only by a sub-process, the data and this sub-process should be synthesized into a function. These data are declared as internal temporary data for this function.

(3) If some data are used several times by a sub-process at different times, the data and this sub-process should be synthesized into a function. This data is defined as the internal static data of the function.

(4), if the function of a sub-process may later be modified or extended, these processes and the number of their use should be synthesized into a class, in order to later use the inherited method to modify and expand its functionality.

(5), when the contradiction between (2), (3) and (4) is contradictory, the (4) shall prevail.

For example, a program that uses a mouse in C + + contains more than 10 sub-processes, such as Mouseopen (), Mousehide (), and so on. If you are implementing a 33H interrupt that calls DOS, because there is no data in common between the various sub-procedures in the program, you should define each sub-procedure as a function.

For example, if you define a data structure that represents a graph, you can zoom in, move, rotate, and so on for the shape. Because these subroutines use common graphical data, these subroutines and these graphical data should be defined as a class.

Vii. use of templates and bids

In Borland C + + 3.1, templates (template) are also introduced to enable powerful bids (Borland international Data structures) through templates Borland C + + 3.1. With bids, you can store data structures of any data type, such as arrays, lists, stacks, and queues, without the need for programming. The following example implements a stack that stores shaping variables:

typedef bi_stackasvector IntStack;

Main ()

{Instack is;//defines a stack of shaping variables

for (int i=0;i<10;i++)

Is.push (I);//10 number Stack

for (i=0;i<10;i++)

cout< number out Stack

}

With the statement Is.push (), Is.pop () can manipulate the stack. The use of bids can be referred to the Borland C + + 3.0 Programmer's Guide.

This article has a background of Borland C + + 3.1, but is suitable for most C + + compilers.

Programming Tips for C + +

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.