Learn about C + + usage

Source: Internet
Author: User
Tags define function function definition

Through the one by one semester of the C + + language learning, I feel C + + is a certain difficult and very challenging subjects, in the C + + learning process, we know that there are many uses.

Reference is a new language feature introduced by C + +, which is one of the most important contents in C + +, and the correct and flexible use of reference can make the program concise and efficient.

Introduction to Citations

A reference is an alias for a variable (the target), and the action on the reference is exactly the same as the direct operation on the variable.

Declarative method of Reference: type identifier & reference name = target variable name;

"Example":
int A; int &ra=a; Defines the reference RA, which is a reference to the variable A, which is the alias

Description

(1) & Here is not the address calculation, but the role of identification.

(2) The type identifier refers to the type of the target variable.

(3) When declaring a reference, it must be initialized at the same time.

(4) When the declaration is complete, the target variable name is equivalent to two names, that is, the target name and reference name, and the reference name cannot be used as an alias for the other variable names.

Ra=1; equivalent to A=1;

(5) Declare a reference, not a new variable, it only means that the reference name is an alias of the target variable name, it is not a data type in itself, so the reference itself does not account for the storage unit, and the system does not assign a storage unit to the reference. Therefore, the reference to the address, that is, the target variable to find the address. &ra is equal to &a.

(6) You cannot create a reference to an array. Because an array is a collection of several elements, you cannot create an alias for an array.

Referencing apps

Reference as parameter

An important function of a reference is as a function parameter. In the previous C language, function parameter passing is a value pass, if there are large chunks of data passed as parameters, the scheme used is often pointers, because this can avoid the whole piece of data stack, can improve the efficiency of the program. But now (c + +) has added an equally efficient choice (which in some special cases is a necessary choice), which is a reference.

"Example":

void swap (int &p1, int &p2)//parameter p1 of the function here, p2 are references
{int p; p=p1; p1=p2; p2=p;}

To call this function in a program, the call point of the corresponding keynote function is called directly with the variable as an argument, without any special requirement of the real parametric. For example: corresponding to the SWAP function defined above, the corresponding keynote function can be written as:

Main ()
{
int A, B;
cin>>a>>b; Enter the value of a, b two variable
Swap (A, b); Call the swap function directly with variables A and B as arguments
cout<<a<< ' <<b; Output results
}

When the above program runs, if the input data 10 20 and enter, then the output is 20 10.

By "Example 2" can be seen:

(1) The effect of passing a reference to a function is the same as passing a pointer. At this point, the parameter of the function is used as the real parametric or an alias of the object in the original central melody function, so the operation of the parameter variable in the function is the operation of its corresponding target object (in the central Melody function).

(2) using the parameters of the reference transfer function, in memory does not produce a copy of the argument, it is directly to the actual parameter operation, while using the general variable transfer function parameters, when a function call, you need to assign a storage unit to the parameter, the parameter variable is the copy of the argument variable; Therefore, when the parameter passes the data is large, uses the reference to pass the parameter with the general variable efficiency and occupies the space to be good.

(3) The use of pointers as parameters of the function, although also can achieve with the use of reference, but in the function of the parameter allocation of the same storage unit, and the need to re-use "* pointer variable name" in the form of operations, which is prone to error and poor program reading; On the other hand, at the call point of the keynote function You must use the address of the variable as the argument. And references are easier to use and clearer.

If you need to use references to improve the efficiency of the program, but also to protect the data passed to the function is not changed in the function, you should use a constant reference.

Reference as return value

To return a function value as a reference, the function definition is formatted as follows:

Type identifier & function name (formal parameter list and type description)
{function Body}

Description

(1) Return function value by reference, need to add & in front of function name when defining function

(2) The greatest benefit of returning a function value with a reference is that it does not produce a copy of the returned value in memory.

The following program defines a normal function fn1 (which returns the function value using the return value method), and a function fn2 that returns the value of the function in the referenced method.

#include <iostream.h>
float temp; Define Global Variables Temp
Float fn1 (float R); Declaring a function fn1
Float &fn2 (float R); Declaring a function fn2
Float fn1 (float R)//define function FN1, which returns the function value as a method of returning a value
{
temp= (float) (r*r*3.14);
return temp;
}
Float &fn2 (float R)//define function FN2, which returns the function value as a reference
{
temp= (float) (r*r*3.14);
return temp;
}
void main ()//main function
{
Float A=FN1 (10.0); In the 1th case, the system generates a copy of the value to return (that is, the temporary variable)
Float &B=FN1 (10.0); 2nd case, error may occur (different C + + systems have different rules)
You cannot return a temporary variable or a reference to a local variable from a function that is being tuned
Float C=FN2 (10.0); In the 3rd case, the system does not generate a copy of the return value
You can return a reference to a global variable from a function that is being tuned
Float &D=FN2 (10.0); In the 4th case, the system does not generate a copy of the return value
You can return a reference to a global variable from a function that is being tuned
cout<<a<<c<<d;
}

Citation summary

In the use of reference, it is meaningless to give the individual name to a variable, and the purpose of the reference is to solve the problem of the transfer efficiency and the space of the large data or object in the function parameter passing. The difference between a reference and a pointer is that the pointer is indirectly manipulated by the variable it points to after it points to an object through a pointer variable. The use of pointers in the program, the readability of the program, and the reference itself is the alias of the target variable, the operation of the reference is the operation of the target variable.


Static usage
To understand static, you must first understand another keyword relative to it, many people may not know that there is this keyword, that is, auto, in fact, we usually declare the variable without static modification, is auto, because it is the default, Just as short and long always default to int; we usually declare a variable:

int A;

string S;

is actually:

auto int A;

Auto string s;

The declaration of the static variable is:

static int A;

static string S;

This seems to be more conducive to understanding that auto and static are pairs of key words, like private,protected,public;
For static does not understand, in fact, is not understanding of auto, because it is more general, and some things you use every day, but not necessarily on behalf of you really understand it; auto means that the lifetime of the variable is automatically controlled by the program, which usually means that the variable is assigned when it enters its scope. is released when it leaves its scope, and static is not auto, and the variable is allocated at program initialization until the program exits, that is, Static is assigned to release the variable according to the program's life cycle, not the variable's own life cycle; So, an example like this:
Voidfunc
{
int A;
static int b;
}
Each time the function is called, the variable A is new because it is allocated when it enters the body of the function and is freed when it exits the body of the function, so multiple threads invoke the function, each of which has its own independent variable A, because it is always reassigned, and the variable b whether or not you use the function, It is assigned when the program is initialized, or when it is first executed to its declaration (different compilers may be different), so when multiple threads invoke the function, they always access the same variable B, which must be noted in multithreaded programming!
Static members of the class:
Class A

{

Private

static int s_value;

};

It must be initialized in the CPP:

int a::s_value = 0;//Note that there is no static modification!

A static member of a class is a common member of all instances of the class, that is, a global variable within the scope of the class, or a global variable named A::s_value, except that it is a class-safe attribute; it is simple because it is allocated at the time of program initialization, so it is allocated only once, So it is shared;

The static member of the class must be initialized, the same is true, because it is allocated at the time of initialization of the program, so there must be initialization, the class is only declared, in the CPP is the initialization, you can put a breakpoint on the initialization code, before the program executes the first statement of main will go to that If your static member is a class, it will be called to its constructor;
Static functions of the class:

Class A

{

Private

static void func (int value);

};

There is no need for static modification when it is implemented, because static is a declarative keyword, a class is a global function within the scope of the class, a private member of the class cannot be accessed, only the static members of the class can be accessed, and no instance of the class can be called; It is a global function that adds access to the class:

void

A::fun (int);

Static member functions can inherit and overwrite, but cannot be virtual functions;
Global functions that are valid only within the CPP:

Declare within CPP:

static void Func ();

The implementation of the function does not require static modification, then this function can only be used within the CPP, and will not conflict with the same name function in other CPP, and if the use of static will cause problems and the 3rd; Do not declare static global functions in the header file. Do not declare a non-static global function in the CPP, if you want to reuse the function in multiple CPP, it will refer to the header file, otherwise it is necessary to add static modification inside the CPP, which is important in C language!

In a word, whether it is static in process-oriented programming or static in object-oriented programming, if we follow the above four points, I believe this difficulty can be solved.

At first learning to feel C + + is a difficult language to learn, and even produced a fear of psychology. In fact, C + + is a difficult to learn and easy to use language, C + + provides too much to choose from, and use C + + to write programs can have four thinking mode: Process-based, object-based, object-oriented and generic. The fact that we use a language to write programs does not mean that we use the language itself, in other words, we use the program library to write programs more often. Learning a language requires skill, and in any language, there are rules. For computer language, I think we should understand it first and then learn to use it.

Learn about C + + usage

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.