References in C + + __c++

Source: Internet
Author: User

One, C + + references:
References introduce a synonym for an object. The presentation of the definition reference is similar to the definition pointer, except that the * is replaced with &. The reference (reference) is an important extension of C + + to the C. language. A reference is an alias to a
variable (target), and the operation of the reference is exactly the same as the direct manipulation of the variable. The format is: type & reference variable name = variable name that has already been defined.
Reference Features:
① A variable is preferable to multiple aliases. The
② reference must be initialized. The
③ reference can only be referenced once at initialization time and cannot be changed to refer to other variables instead.
1, base reference

 #include <stdio.h> int main () {int i = 5;
    int j = i;

    int &k = i;
    printf ("I.val =%d, i.addr =%x\n", I, &i);
    printf ("J.val =%d, j.addr =%x\n", j, &j);

    printf ("K.val =%d, k.addr =%x\n", K, &k);
    printf ("Modify the value of I: \ n");
    i = 6;//modifies the value of I, the value of K also modifies printf ("I.val =%d, i.addr =%x\n", I, &i);
    printf ("J.val =%d, j.addr =%x\n", j, &j);

    printf ("K.val =%d, k.addr =%x\n", K, &k);
    printf ("Modify K value: \ n");
    K = 7;//modifies the value of K, and the value of I also modifies printf ("I.val =%d, i.addr =%x\n", I, &i);
    printf ("J.val =%d, j.addr =%x\n", j, &j);

    printf ("K.val =%d, k.addr =%x\n", K, &k);
return 0; //output: I.val = 5, i.addr = 33f794 J.val = 5, j.addr = 33f788 K.val = 5, k.addr = 33f794 Modify value of I: I.val = 6, i.addr = 33f7 J.val = 5, j.addr = 33f788 K.val = 6, k.addr = 33f794 Modify K value: I.val = 7, i.addr = 33f794 J.val = 5, j.addr = 33f788 K.va L = 7, k.addr = 33f794, press any key to continue ... 

2. Const reference

#include <stdio.h>      

int main ()  
{  
    int d1 = 4;
    const int & d2 = D1;
    D1 = 5;//d1 Change, d2 value will also change.
    //D2 = 6;//cannot assign a value to a constant (a quantity that cannot be modified).

    const int d3 = 1;
    const int & d4 = D3;
    INT&D5 = D3;
    const int & d6 = 5;    Constants have constancy, and only regular references can refer to constants

    double d7 = 1.1;
    int& D8 = D7;//d7 is a double type, D8 is to generate a temporary variable when INT,D7 is assigned to D8
                   //That is, the D8 refers to this temporary variable with constancy, so it cannot be assigned a value.
    const int& D9 = d7;//Using a constant reference is achievable return
    0;
}  

3. Reference as parameter

1. "Value delivery" if the parameter is a value-only method that is not referenced, a local temporary variable is generated to receive the value of the argument
void Swap (int left, int right) 
{                    
     int temp = left;
     left = right;
     right = temp;
}
The value is passed in a way that cannot be exchanged because a temporary copy of the parameter left and right is exchanged when the argument is transferred, because it is the temporary variable function exit, the variable is destroyed, and the external left and right values are not affected.

2. "Reference delivery" if the formal parameter is a reference type, then the formal parameter is an alias for the argument.
void Swap (int& left, int& right)
{
     int temp = left;
     right = left;
     left = temp;
}
Using references, do not make temporary copies of the use of,& is only the original parameter of the other name, so modify the original parameter directly on the basis of the modified variable value.

3. "Pointer pass"
void Swap (int* pleft, int* pright)
{
     int temp = *pleft;
     *pleft = *pright;
     *pright = temp;
}
The address is passed in, because the address is unique, so the pointer can then modify its contents by accessing the address.

Instance:

 #include <stdio.h> void Swap1 (int left, int right) {int T
     EMP = left;
     left = right;
right = temp;
     } void Swap2 (int& left, int& right) {int temp = left;
     left = right;
right = temp;
     } void Swap3 (int* pleft, int* pright) {int temp = *pleft;
     *pleft = *pright;
*pright = temp;
    int main () {int a = 1;
    int b = 2;
    Swap1 (A, b);

    printf ("A =%d, B =%d\n", A, b);
    Swap2 (A, b);

    printf ("A =%d, B =%d\n", A, b);
    SWAP3 (&a, &b);
    printf ("A =%d, B =%d\n", A, b);
return 0; ///Output Result: A = 1, b = 2//not exchanged A = 2, b = 1//Exchanged a = 1, b = 2//exchanged (based on last result) Press any key to continue ... 

The reference is convenient and must be used with caution:
(1) & here is not to find the address operation, but to play 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) After the declaration of the reference, the equivalent of the target variable name has two names, that is, the target's original name and reference name, and can no longer be used as an alias for other variable names.
(5) To address the reference, that is, the target variable to find the address. That is, the reference name is an alias to the target variable name. A reference is defined to mean that the reference does not occupy any memory space, but the compiler generally implements it as a const pointer, which points to an immutable pointer, so that the reference actually occupies the same memory as the generic pointer.
(6) An array of references cannot be established. Because an array is a collection of several elements, you cannot establish a collection of references, but you can establish a reference to an array.
(7) Reference common usage: As a function parameter, function return value.

Summarize:
1. Do not return a reference to a temporary variable.
2. If the return object is out of scope for the current function, it is best to return with the reference because it is more efficient.

Differences and links between references and pointers: (written topic)
1. References can only be initialized once at the time of definition and cannot be changed to point to other variables (one-woman), and the values of pointer variables are variable.
2. The reference must point to a valid variable and the pointer can be empty.
3. SizeOf pointer objects and reference objects have different meanings. The sizeof reference gets the size of the variable being pointed to, and the sizeof pointer is the size of the object's address.
4. Pointers and citations (+ +) self-subtraction (–) have different meanings.
5. In contrast, references are more secure than pointers.

pointers are more flexible than references, but they are risky. When using the pointer, be sure to check whether the pointer is empty (NULL), and after the space is recycled, the pointer is best zero to avoid the occurrence of the wild pointer caused by memory leaks and so on.

Ii. differences and links between references and pointers:

★ Different points:
1. The pointer is an entity and the reference is only an individual name;
2. References need not be referenced (*), the pointer needs to dereference;
3. References can only be initialized once at the time of definition, and then immutable, and the pointer is variable;
4. The reference does not have a const, the pointer has const;const modification of the pointer is immutable;
5. The reference cannot be null, the pointer can be empty;
6. The "sizeof reference" obtains the size of the variable (object) to which it is pointed, and the "sizeof pointer" gets the size of the pointer itself (the address of the variable or object to which it is directed);
7. The pointer and the reference of the self-increase (+ +) operation is not the same meaning;
8. See from memory allocation: The program allocates memory areas for pointer variables, and references do not need to allocate memory regions.

★ The same point:
Both are the concept of an address, the pointer points to a memory, the content of which is the address of the memory, the reference is a block of memory alias.

Third, the const in C and C + + meaning (written hot):

⑴c in the const, the function is relatively single, easier to understand:
Function: The content that is decorated cannot be changed.
Usage: modifier variables, function parameters, return values, and so on. (c + + in the application of the situation is much richer)
Features: Runtime const, and therefore cannot replace #define used to become the length of the array, such as the need to compile a constant amount of time. Also, because it is run-time const, it can be defined, not initialized, and initialized at run time. such as const int iconst;. In addition, in C, the const variable defaults to an external link, so if you have a const variable with the same name in a different compilation unit, a naming conflict is raised, and the compilation times is wrong.

Const in

⑵c++:
A, non-class member Const:
①const variables are internally connected by default, so you can have a const variable definition in a different compilation unit with the same name. The
② compile-time, so it can be used like #define, and because of the above, you can define a const variable in a header file that is used in a different CPP file (compilation unit) without causing a naming conflict.
The ③ compiler does not allocate memory for the const variable by default unless: 1. use extern declaration, 2: The address in the program that references the const variable. The temporary object/built-in variable in the
④c++ has a const attribute by default.
B, the const in the class:
①, like the const in C, is just a running constant and cannot be used as an array dimension, that is, it cannot be substituted for #define. Use the following two methods in the class to replace the #define:1:static const ... 2:enum{....}//enum does not occupy storage space. The const variable in the
② class occupies storage space. The const member variable in the
③ class needs to be initialized in the constructor initialization list.
④const object: Within the life cycle of the object, no member variables must be guaranteed to be changed. The const object can only invoke const member functions.
⑤const member function: void fun () const ... Can be invoked not only by a const object, but also by a non-const object, so if you confirm that any member function does not change any member variables, you should habitually define the function as a const type.
⑥ If an object is defined as const, then the Const object "may" be put into ROM, which is sometimes very important in embedded development.

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.