C + + Reference

Source: Internet
Author: User

In the process of learning C + +, the understanding of the concept of reference is not deep, the programming process is always wrong, so the reference to the understanding of the following records

I. Definitions of references

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 1": 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) When declaring a reference, it must be initialized at the same time.

(3) 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.

Second, Reference Application

1. An important function of reference as a parameter 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.

Cases

void swap (int &p1, int &p2) {

int p;

P=P1;

P1=P2;

P2=p; }

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.

2. Frequently quoted

Common Reference declaration method: Const type identifier & reference name = target variable name;

A reference declared in this way cannot be modified by reference to the value of the target variable, thus making the target of the reference a const, which achieves the security of the reference.

3. 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.

Cases

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

Reference as the return value, the following rules must be observed:

(1) A reference to a local variable cannot be returned. This article can refer to effective c++[1] Item 31. The main reason is that the local variable is destroyed after the function returns, so the returned reference becomes a "no" reference, and the program goes into an unknown state.

(2) You cannot return a reference to the memory that is allocated inside the function. This article can refer to effective c++[1] Item 31. Although there is no passive destruction of local variables, there are other embarrassing situations in which the case (a reference to new allocation of memory within the function) is returned. For example, a reference returned by a function is only present as a temporary variable, not given an actual variable, and the space pointed to by the reference (allocated by new) cannot be freed, resulting in memory leak.

(3) A reference to a class member can be returned, but preferably a const. This principle can be referenced by effective C++[1] Item 30. The main reason is that when an object's property is associated with a business rule, its assignment is often related to the state of some other attribute or object, so it is necessary to encapsulate the assignment in a business rule. If other objects can get a very good reference (or pointer) to the property, the simple assignment of that property will break the integrity of the business rules.

(4) Overloading of references and some operators:

Stream operators << and >>, these two operators often want to be used continuously, for example: cout << "Hello" << Endl; Therefore, the return value of these two operators should be a stream reference that still supports both operators. Alternative options include returning a stream object and returning a pointer to a stream object. But for a stream object to be returned, the program must recreate (copy) a new stream object, that is to say, two consecutive << operators are actually for different objects! It's not acceptable to anyone. The << operator cannot be used consecutively for returning a stream pointer. Therefore, returning a Stream object reference is the only option. This unique choice is key, it shows the importance of the reference and the irreplaceable, perhaps this is the introduction of the concept of reference in the C + + language is the reason for it. Assignment operator =. This operation, like the Fuchang operator, can be used consecutively, for example: x = j = 10, or (x=10) = 100; The return value of the assignment operator must be an lvalue so that it can be assigned again. The reference is therefore the only return value selection for this operator.

The "Example 6" test uses the value of the function that returns the reference as the lvalue of the assignment expression.

#include <iostream.h>
int &put (int n);
int vals[10];
int error=-1;
void Main ()
{
Put (0) = 10; The value of the put (0) function as the left value is equivalent to vals[0]=10;
Put (9) = 20; The value of the put (9) function as the left value is equivalent to vals[9]=20;
cout<<vals[0];
cout<<vals[9];
}
int &put (int n)
{
if (n>=0 && n<=9) return vals[n];
else {cout<< "subscript error"; return error;}
}

(5) In some other operators, it is not possible to return a reference: +-*/arithmetic character. They cannot return references, effective c++[1] Item23 detailed discussion of this issue. The main reason is that these four operators do not have side effect, so they must construct an object as the return value, and the optional scheme includes returning an object, returning a reference to a local variable, returning a reference to a new allocated object, and returning a static object reference. According to the preceding reference as the three rules for the return value, the 2nd and 32 scenarios are deprecated. A reference to a static object also causes an error because ((a+b) = = (C+d) is always true. So the only option left is to return an object.

4. References and polymorphism

A reference is another means of producing a polymorphic effect, in addition to pointers. This means that a reference to a base class can point to its derived class instance.

Example :

Class A;
Class B:public a{...};
b b;
A &ref = b; To initialize a reference to a base class object with a derived class object

Ref can only be used to access the members inherited from the base class in the derived class object, which is the base class reference to the derived class. If a virtual function is defined in Class A, and the virtual function is overridden in class B, a polymorphic effect can be generated by ref.

  Iii. Summary of citations

(1) In the use of reference, it is meaningless to simply give a certain variable name, the purpose of the reference is mainly used in the transfer of function parameters, to solve the problem of the transfer efficiency and the space of large data or objects.

(2) using the parameters of the reference transfer function, it can ensure that the parameters are not generated in the transfer of the copy, improve the efficiency of the transfer, and through the use of const, to ensure the security of reference delivery.

(3) 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.

(4) The timing of the use of references. Reference is recommended for the stream operator << and >>, the return value of the assignment operator =, the parameter of the copy constructor, the parameter of the assignment operator =, and other cases.

C + + Reference

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.