C + + programming skills synthesis

Source: Internet
Author: User
Tags abs data structures

C + + language is an object-oriented language, the use of C + + written code more simple, efficient, more maintainable and reusable. But many people use the C + + language but feel C + + and C programming is no different. This is actually due to the C + + language characteristics and characteristics of understanding and use of not enough. In fact, no programmer can use the C language programming efficiency to exceed the C + + language.

Use new and delete for dynamic memory allocation and release

Operators new and delete are new operators in C + + that provide dynamic allocation and deallocation of storage. It acts as a function of the C language malloc () and free (), but the performance is superior. There are several advantages to using new than using malloc ():

(1), new automatically calculate the size of the type to be allocated, do not use the sizeof operator, more convenient, you can avoid errors.

(2) It automatically returns the correct pointer type without forcing pointer type conversions.

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

Use examples:

(1), int *p;

P=new INT[10]; Assign a shape array with 10 integers

Delete[] p; Delete this array

(2), int *p;

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

Second, use the inline function to replace the 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. However, there are many drawbacks of macro invocation, which may cause undesirable side effects. such as macros:

#define ABS (a) ((a) <0? ( -a): (a) when using ABS (i++), the macro will be faulted.

So in C + + should use the inline function to replace the macro call, so you can achieve the function of macro invocation, and avoid the drawbacks of macro invocation.

Using the inline function simply puts the inline key word in front of the function return type. For example:

inline int Add (int a,int b);//Declaration ADD () is an inner-link function

When the compiler encounters the Add () function, it no longer makes a function call, but embeds the function code directly to speed up the execution of the program.

Third, use function overload

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

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

void Puthz (int x,int y,char *str); Output Chinese characters at X,y

Using a function overload can help programmers cope with more complexity, avoid the use of complex functions such as intabs (), Fabs (), Dabs (), and in large programs, make function names easy to govern and use without having to grapple with function names.

Using reference (reference) instead of pointers for parameter passing

In C, if a function needs to modify the value of a variable used as a parameter, the argument 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 error, the program is difficult to read. In C + +, references can be used instead of pointers to make the program clearer and easier to understand. A reference is an alias to a variable, and manipulating the reference is equivalent to manipulating the original variable. , such as using a referenced function to define:

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

This function is the same as the function that uses the previous function of the pointer, but the code is simpler and easier to understand.

V. Use 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 function Puthzxy (), for example:

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

Puthzxy ("C + + language", 10,10); a function should have as much flexibility as possible, using default parameters to provide an effective way for programmers to handle greater complexity and flexibility. Therefore, in C + + code is a large number of use of the default parameters.

It is important to note that all default parameters must appear to the right of the not-default parameters. That is, once you start to define the parameters that take the default values, you can no longer explain the 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 six, use "class" to seal the data

C language is a modular programming language, through the use of functions and the separate compilation of files to achieve a certain data encapsulation function. But C + + uses the powerful features of "classes" to do better than C in terms of data encapsulation, continuing, and so on. By encapsulating the data and the collection of all the operations of the data by using "class", a well-defined interface is created so that programmers can only care about its use when using a class, without having to care about its implementation.

Because functions can also achieve a certain degree of encapsulation of the data, when writing C + + programs when the use of functions, when the use of classes, for C + + beginners difficult to grasp. According to the author's experience, for the use of functions and classes summed up the following methods:

First, the function that the program needs to complete is divided into many basic processes, and a sub process realizes a relatively complete function. They are then divided according to the following rules:

(1) If some data is used at the same time by more than two sub processes, the data and these subroutines should be encapsulated using "class".

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

(3) If some data is used several times by a subroutine in different time, the data should be synthesized into a function with the child process. This data is defined as the internal static data for this function.

(4) If the function of a subroutine may be modified or expanded in the future, the process and the number it uses should be synthesized into a class so that its function can be modified and expanded later using the continuation method.

(5), when (2), (3) and (4) are 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 calling a DOS 33H interrupt, you should define each subroutine as a function because there is no shared data between the various child processes in the program.

For example, if you define a data structure that represents a graphic, enlarge, move, and rotate the graph. Because these subroutines use public graphic data, you should define these subroutines and the graphic data as a class.

Vii. use of templates and bids

The feature of template (template) is also introduced in Borland C + + 3.1, which enables powerful bids (Borland International Data structures) through templates Borland C + + 3.1. Using bids, you can store data structures of any data type, including arrays, lists, stacks, queues, and so on without 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 of pressure stacks

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

cout<}

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

This article is based on Borland C + + 3.1, 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.